jquery插件ajaxfileupload可以实现ajax文件上传,该插件使用非常简单,首先了解一下正确使用ajaxfileupload插件的方法,然后再了解一些常见的错误信息和解决方法。
使用说明
需要使用jquery库文件 和ajaxfileupload库文件
使用实例
一,包含文件部分
复制代码 代码如下:
二,html部分
复制代码 代码如下:
上传
只需要三个元素,一个动态加载小图标、一个文件域和一个按钮
注意:使用ajaxfileupload插件上传文件可不需要form,如下:
……相关html代码……
因为ajaxfileupload插件会自动生成一个form提交表单。对于file文件域id和name,ajaxfileupload插件fileelementid参数需要获取文件域id,如果处理上传文件操作就需要知道文件域name,以便获取上传文件信息,这两者关系一定要清楚。
三,javascript部分
主要参数说明:
1,url表示处理文件上传操作的文件路径,可以测试url是否能在浏览器中直接访问,如上:upload.php
2,fileelementid表示文件域id,如上:filetoupload
3,secureuri是否启用安全提交,默认为false
4,datatype数据数据,一般选json,javascript的原生态
5,success提交成功后处理函数
6,error提交失败处理函数
上面有两个方法,一个动态加载小图标提示函数loading()和ajaxfileupload文件上传$.ajaxfileupload()函数,这与我们使用jquery.ajax()函数差不多,使用很简单,这里我省略了php处理上传文件,使用jquery插件 ajaxfileupload实现ajax文件就这么简单。
同时我们需要了解相关的错误提示
1,syntaxerror: missing ; before statement错误
如果出现这个错误就需要检查url路径是否可以访问
2,syntaxerror: syntax error错误
如果出现这个错误就需要检查处理提交操作的php文件是否存在语法错误
3,syntaxerror: invalid property id错误
如果出现这个错误就需要检查属性id是否存在
4,syntaxerror: missing } in xml expression错误
如果出现这个错误就需要检查文件域名称是否一致或不存在
5,其它自定义错误
大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。
使用jquery插件ajaxfileupload实现无刷新上传文件非常实用,由于其简单易用,因些这个插件相比其它文件上传插件使用人数最多,非常值得推荐。
处理页面:
using system;using system.collections;using system.configuration;using system.data;using system.web;using system.web.security;using system.web.ui;using system.web.ui.htmlcontrols;using system.web.ui.webcontrols;using system.web.ui.webcontrols.webparts;public partial class web_ajax_fileupload : system.web.ui.page{ protected void page_load(object sender, eventargs e) { httpfilecollection files = httpcontext.current.request.files; //if (files[0].contentlength > 5) //{ // response.write({); // response.write(msg:' + files[0].filename + ',); // response.write(error:'文件上传失败'); // response.write(}); //} //else //{ // response.write({); // response.write(msg:'没有文件被上传',); // response.write(error:'文件上传失败'); // response.write(}); //} files[0].saveas(d:/adw.jpg); response.write({); response.write(msg:'a',); response.write(error:''); response.write(}); //response.write({); //response.write(msg:'ggg\n',); //response.write(error:'aa\n'); //response.write(}); response.end(); }}
其它网友的补充:
页面代码:
复制代码 代码如下:
服务器代码:
复制代码 代码如下:
public class updateaction extends dispatchaction { public actionforward uploader(actionmapping mapping, actionform form,
httpservletrequest request, httpservletresponse response) {
upformform upformform = (upformform) form;
formfile ff = upformform.gethousemaps();
try {
inputstream is = ff.getinputstream();
file file = new file(d:/ + ff.getfilename()); //指定文件存储的路径和文件名
outputstream os = new fileoutputstream(file);
byte[] b = new byte[1024];
int len = 0;
while((len = is.read(b)) != -1){
os.write(b, 0, len);
}
os.close();
is.close();
} catch (exception e) {
e.printstacktrace();
}
return null;
}
}
