Ajax编程的文件上传下载问题

JFinal使用ajaxfileupload实现图片上传 及预览
1.前端页面核心代码
&script type=&text/javascript& src=&&%=request.getContextPath() %&/js/jquery.min.js&&&/script&
&script type=&text/javascript& src=&&%=request.getContextPath() %&/media/ajaxupload/ajaxfileupload.js&&&/script&
&input type=&file& class=&upload& name=&file& id=&upfile& onchange=&ajaxFileUpload('upfile')&/&
&!--用于预览图片--&
&img src=&&c:if test=&${banner.img!=null}&&&%=request.getContextPath() %&/media/file/${banner.img}&/c:if&& style=&width:300height:100& id=&imgsrc&/&
&!--存放图片路径,提交页面时传给后台的值--&
&input id='imgurl' type='hidden' name=&imgurl& style=&height:30width:100%& value='${banner.img}'/&
function ajaxFileUpload(fileEid, paramdata){
if(typeof(paramdata)=='undefined') paramdata = {};
var $file=$('#'+fileEid).val();
if($file=='') {alert(&请先选择对应的上传文件,谢谢&);}
$.ajaxFileUpload({
url:'&%=request.getContextPath()%&/banner/uploadpic',
secureuri:false,
fileElementId:fileEid,
dataType: 'text',
data:paramdata,
success: function (result){
var result = result.substring(result.indexOf(&{&),result.indexOf(&}&)+1);
result = eval(&(&+result+&)&);
if(result.t==1){
$(&#imgsrc&).attr(&src&,&&%=request.getContextPath() %&/media/file/&+result.msg);
$(&#imgurl&).val(result.msg);
alert(&上传失败&);
2.后台核心代码
public void uploadpic(){
UploadFile upfile = getFile();//JFinal规定getFile()必须最先执行
File file = upfile.getFile();
String filename = file.getName();
String delfilename =
if(filename!=null && !filename.equals(&&)){
filename = new SimpleDateFormat(&yyyyMMddkkmmss&).format(new Date())+
* 新保存的位置
String path = getRequest().getSession().getServletContext()
.getRealPath(&/&);
String newPath = &/media/file/&;//自定义目录
用于存放图片
* 没有则新建目录
File floder = new File(path + newPath);
if (!floder.exists()) {
floder.mkdirs();
* 保存新文件
FileInputStream fis =
FileOutputStream fos =
File savePath = new File(path + newPath + filename);
if(!savePath.isDirectory()) savePath.createNewFile();
fis = new FileInputStream(file);
fos = new FileOutputStream(savePath);
byte[] bt = new byte[300];
while (fis.read(bt, 0, 300) != -1) {
fos.write(bt, 0, 300);
}catch(Exception e){
e.printStackTrace();
if(null!=fis) fis.close();
if(null!=fos) fos.close();
}catch(Exception e){
e.printStackTrace();
* 删除原图片,JFinal默认上传文件路径为 /upload(自动创建)
File delFile = new File(path+&/upload/&+delfilename);
if(delFile.exists()){
delFile.delete();
setAttr(&msg&,filename);
setAttr(&t&,1);
setAttr(&t&,0);
renderJson();
附:ajaxfileupload.js代码
jQuery.extend({
createUploadIframe: function(id, uri) {
//create frame
var frameId = 'jUploadFrame' +
var iframeHtml = '&iframe id=&' + frameId + '& name=&' + frameId + '& style=&position: top:-9999 left:-9999px&';
if(window.ActiveXObject) {
if(typeof uri== 'boolean'){
iframeHtml += ' src=&' + 'javascript:false' + '&';
} else if(typeof uri== 'string'){
iframeHtml += ' src=&' + uri + '&';
iframeHtml += ' /&';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
createUploadForm: function(id, fileElementId, data) {
//create form
var formId = 'jUploadForm' +
var fileId = 'jUploadFile' +
var form = jQuery('&form
action=&& method=&POST& name=&' + formId + '& id=&' + formId + '& enctype=&multipart/form-data&&&/form&');
if(data) {
for(var i in data) {
jQuery('&input type=&hidden& name=&' + i + '& value=&' + data[i] + '& /&').appendTo(form);
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' +
var formId = 'jUploadForm' +
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( &ajaxStart& );
var requestDone =
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger(&ajaxSend&, [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
var io = document.getElementById(frameId);
if(io.contentWindow) {
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.
} else if(io.contentDocument) {
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.
} catch(e) {
jQuery.handleError(s, xml, null, e);
if ( xml || isTimeout == &timeout&) {
requestDone =
status = isTimeout != &timeout& ? &success& : &error&;
// Make sure that the request was successful or notmodified
if ( status != &error& ) {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( &ajaxSuccess&, [xml, s] );
jQuery.handleError(s, xml, status);
} catch(e) {
status = &error&;
jQuery.handleError(s, xml, status, e);
// The request was completed
if( s.global )
jQuery.event.trigger( &ajaxComplete&, [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( &ajaxStop& );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function() {
jQuery(io).remove();
jQuery(form).remove();
} catch(e) {
jQuery.handleError(s, xml, null, e);
xml = null
// Timeout checker
if ( s.timeout & 0 )
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( &timeout& );
}, s.timeout);
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding) {
jQuery(form).attr('encoding', 'multipart/form-data');
jQuery(form).attr('enctype', 'multipart/form-data');
jQuery(form).submit();
} catch(e) {
jQuery.handleError(s, xml, null, e);
jQuery('#' + frameId).load(uploadCallback);
return {abort: function () {}};
uploadHttpData: function( r, type ) {
var data = !
data = type == &xml& || data ? r.responseXML : r.responseT
// If the type is &script&, eval it in global context
if ( type == &script& )
jQuery.globalEval( data );
// Get the Script object, if JSON is used.
if ( type == &json& )
eval( &data = & + data );
// evaluate scripts within html
if ( type == &html& )
jQuery(&&p&&).html(data).evalScripts();当前位置:
(ajax)微信内网页上传图片问题
(ajax)微信内网页上传图片问题
来源:网络整理&&&&&时间: 1:38:12&&&&&关键词:网页上传,上传图片
关于网友提出的“(ajax)微信内网页上传图片问题”问题疑问,本网通过在网上对“(ajax)微信内网页上传图片问题”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题:(ajax)微信内网页上传图片问题
描述:目前在实现微信平台内的小功能,类似于个人名片需要填写个人信息啊, 头像之类的问题是写好的功能在微信端不能上传, 在浏览器里可以, 可能是微信给屏蔽了,我使用的是 js经过base64转码后 Ajax提交, 也就是网上的例子,
我目前把demo放到了网上,你可以看下,顺便想知道怎么解决请在微信端打开demo谢谢解决方案1:试试Web Uploader
http://fex.baidu.com/webuploader/解决方案2:微信并没有对type=file做任何特殊处理。但是在Android 4.4.1/4.4.2系统中,这的确没法使用。其它版本中如果客户端如果需要对H5的 &input& 标签做支持,即在H5支持选择文件的功能,可以通过重写WebViewClient非public的openFileChooser方法来实现。可在4.4.1/4.4.2系统中,该回调方法被废弃,客户端无法捕获用户在H5页面上对&input&标签的点击。谷歌官方也未对此给出任何解释或可行的替代方案:参考链接建议使用微信提供的js-sdk来做文件上传的相关功能解决方案3:http://blueimp.github.io/jQuery-File-Upload/basic.html可以用这个插件来上传文件;
以前发现个BUG:在Andriod kikkat中的微信上不能上传;刚才试了下Andriod Lollipop上竟然可以上传了;解决方案4:最新的js-sdk http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e48dd613f.html解决方案5:微信内置浏览器禁止了 直接使用 type=file 进行文件上传 可以使用jQuery插件 ajaxfileupload
以上介绍了“(ajax)微信内网页上传图片问题”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/1059001.html
上一篇: 下一篇:扫码加入我们
I see that it uses browser sniffing to detect Safari (browser sniffing is usually frowned upon), so progressFrame is only used with Safari/Chrome (I don't know why). The part where the error is occurring seems to be where the script tries to reference progressFrame just by looking for its name in the global scope instead of using a function like document.getElementsByName.
日22分43秒
I'm not sure what you mean by &send it using AJAX when it is completed& -- Isn't the progress bar representing the progress of the submission?
Doesn't that mean that it is already sent once it is complete? Do you mean that you want the original form submission to be driven by AJAX so it doesn't cause a page refresh after?
日00分03秒
Yes, but it acts like a form submission.
Thats exactly what I want.
日22分43秒
If the question how do you send data with an HTTP POST over XMLHttpRequest using jQuery, then there is jQuery.post
日22分43秒
Do the answers below work for you?
If not, can you comment on the answers.
I'm slightly confused as a result of all of the edits and want to try to solve your problem.
BTW I included a link for JQuery's Multiple File upload plugin.
日22分43秒
IE 9 don't know this. :(
日00分09秒
This is a feature available only in XMLHttpRequest2, for a full compatibility list - have a look at caniuse.com/xhr2
日22分43秒
Rudie Do you have the hotblocks.nl tutorial link?
not just the demo Thanks in adv
日22分43秒
There's no tutorial. Never wrote it. Didn't even make the demo to be this public.
日22分43秒
NeilMartin I've added PHP example code to the end of the answer. Obviously you'll want to do something else with it.
日22分43秒
i used plUpload in several projects with success (multi file upload with progress, supports Flash/Html5/Silverlight etc)
日22分43秒
AjaxFileUpload is a piece of crap. It's not compatible with any version of jquery newer than 1.5. Also the code is wicked ugly.
日22分43秒
Adam - Good to know. I guess a lot changes in a year. Our hair gets a little greyer and JavaScript libraries stop working with newer software versions...
日22分43秒
To expand Adam, AjaxFileUpload breaks on ie9+
日22分43秒
RanaMuhammadUsman - Take another look now. I believe I found the location of the moved plugins. Hope this helps.
日22分43秒
& 2017 内容协议后台用springMVC,方法定义如下:
public @ResponseBody FeedResult saveOrUpdateWorks(AddForm form, HttpServletRequest request, HttpServletResponse response) {//逻辑}
ie系列会提示下载
提示下载解决办法1:
&property name="supportedMediaTypes"&
&!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 --&
&value&text/charset=UTF-8&/value&
&value&text/charset=UTF-8&/value&
&value&application/charset=UTF-8&/value&
&/property&但该方法有个局限性,就是中后期的项目改动比较大,会影响所有接口,并且所有ajax方法dataType都要改为json,不然会返回undefined(印象中);
2.方法二,只针对单个接口:
修改上面的方法,但返回值变成voidpublic void saveOrUpdateWorks(WorkAddForm form, HttpServletRequest request, HttpServletResponse response) {//逻辑Json.writeObj(jResult, response);//通过这种返回
writeObj()做的事情如下:
//主要是这句:rsp.setContentType("text/charset=UTF8");
但第二种在ie8里有出现了另外一种情况,发起两次请求到后台接口,导致不进回调方法:
瞎搞了半天,原来发现有前人遇到:
http://blog.csdn.net/tudopi/article/details/5577562
就是在$(this).attr('submited',true).ajaxSubmit({});后终止它,即紧接着写:
ie8兼容性问题(八)
jquery——ajaxSubmit
IE8,IE9不支持ajaxSubmit
SpringMVC ajaxFileUpload 上传图片 IE8 已测
IE8+Win7下ajaxSubmit异常问题 提示缺少对象 jquery.min.js
jquery-form中ajaxSubmit提交文件,以及解决ie9下上传文件后自动下载问题
form.js插件
利用ajaxSubmit上传文件时ie总出现下载提示框
没有更多推荐了,MVC+AjaxFileUpload文件上传_ASP.NET技巧_动态网站制作指南
MVC+AjaxFileUpload文件上传
来源:人气:998
本次给大家分享的是fileupload文件上传插件,百度一大堆功能超炫的文件上传插件,为什么我们会选择这个插件呢?
原因是在此之前,我们尝试使用过很多基于的上传插件,但由于兼容性,适用性等诸多问题,最终我们选择了&ajaxfileupload.js,由于它使用的原生input标签实现,兼容性很好,它的原理和用法我就不多说了,很多大神们都分析的很透彻。本次和大家分享一下使用它时遇到的各种'坑',希望大家在使用的时候有所规避。
1.类型问题
& 如下图,网上大多数资料都说类型dataType一般使用json
但是使用json格式在火狐浏览器中会解析异常提示下载。
解决办法:
使用dataType:&html&,也有网友说在某些版本浏览器中html要大写成HTML才起作用 ,目前没有发现此问题。
在控制器返回Json格式数据的时候,处理一下ContentType:return Json(new { Success = true, Message = "文件上传成功" }, "text/html");
2.插件调整
下载回来使用时需要检查插件中的这段代码:var io = document.createElement('&iframe id="' + frameId + '" name="' + frameId + '" /&');改成:var io = document.createElement("iframe");io.id = frameId;io.name = frameId;第一句代码在IE部分版本中提示InvalidCharacterError 错误导致无法运行
3.input透明法
先列举一种用法,如图:
&input type="file" id="upload" &&input type="button" value="上传" onlick="document.getElementById(&upload&).click()"/&如上图点击button模拟点击input/file标签选择文件上传,这种方式在IE8中无法执行,原因IE8要求比较严格,出于安全限制无法更改value值和促发change事件。
解决办法:采用input透明法
.file_btn_visible{position:top:-30left:0;width:80height:30cursor:opacity:0;filter:alpha(opacity=0);}意思就是说将input[type=file] 标签通过样式放置在自定义按钮的上面,然后将input透明度设为0(opacity:0;filter:alpha(opacity=0)),此时点击按钮时实际上点击的是file标签,就不会有问题了。调整后的插件兼容ie7/8/9/10/11、、等浏览器,注意的是jQuery版本需使用2.0以下的版本,高版本jQuery已不支持IE6/7/8ajaxfileupload功能虽没有其他flash控件功能强大,但对于普通单文件上传效果很好,运用场景比如:上传图像,上传用户身份证,普通图片,文件等以上是实际开发过程中遇到的部分问题,若有其他疑问可在公众号留言。
原文链接:http://mp.weixin..com/s?__biz=MzIzNTE2OTk1MA==&mid=&idx=1&sn=0f091d8a9ebf006f5e5de63#rd
相关资源获取或其他疑问可在扫码添加CodeL公众号留言。(微信公众号: codelir)
微信扫一扫获取更多开发资源:
优质网站模板}

我要回帖

更多关于 文件上传协议 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信