ajaxFileUpload 异步上传文件简单使用

前端之家收集整理的这篇文章主要介绍了ajaxFileUpload 异步上传文件简单使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

ajaxFileUpload 异步上传文件简单使用

原创 2014年07月18日 17:36:26
[html] view plain copy
copy
    <%@pagelanguage="java"contentType="text/html;charset=UTF-8"
  1. pageEncoding="UTF-8"%>
  2. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
  3. <htmlheadMetahttp-equiv="Content-Type"content="text/html;charset=UTF-8"title>Inserttitlehere</
  4. <!--引用jquery-->
  5. scriptsrc="//code.jquery.com/jquery-1.11.0.min.js">scriptscriptsrc="//code.jquery.com/jquery-migrate-1.2.1.min.js"<!--引用ajaxfileupload.js-->
  6. scriptsrc="../js/ajaxfileupload.js"
  7. scripttype="text/javascript" $(function(){
  8. //点击打开文件选择器
  9. $("#upload").on('click',function(){
  10. $('#fileToUpload').click();
  11. });
  12. //选择文件后执行上传
  13. $('#fileToUpload').on('change',function(){
  14. $.ajaxFileUpload({
  15. url:'../FileUploadServlet',
  16. secureuri:false,
  17. fileElementId:'fileToUpload',//file标签的id
  18. dataType:'json',//返回数据的类型
  19. data:{name:'logan'},//一同上传的数据
  20. success:function(data,status){
  21. //把图片替换
  22. varobj=jQuery.parseJSON(data);
  23. $("#upload").attr("src","../image/"+obj.fileName);
  24. if(typeof(data.error)!='undefined'){
  25. if(data.error!=''){
  26. alert(data.error);
  27. }else{
  28. alert(data.msg);
  29. }
  30. }
  31. },248); line-height:18px; margin-top:0px!important; margin-right:0px!important; margin-bottom:0px!important; padding:0px 3px 0px 10px!important"> error:function(data,status,e){
  32. alert(e);
  33. });
  34. body <!--点击图片,打开文件选择器,确定,上传。(这是网络上的一个图片)-->
  35. imgid="upload"alt=""style="width:200px;height:200px"
  36. src="http://d.pcs.baidu.com/thumbnail/e8119cd92364a9b2714ea0a92af15aec?fid=2399642819-250528-305026848845811&time=1405674000&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-abo3xnZkLb7yMEPLDWiuaQI8kXM%3D&rt=sh&expires=2h&r=900585425&sharesign=unknown&size=c710_u500&quality=100"<!--隐藏file标签-->
  37. inputid="fileToUpload"style="display:none"type="file"name="upfile"br/>
  38. >


[java] copy
    packagecom.yangshidesign.weixinface.servlet;
  1. importjava.io.File;
  2. importjava.io.IOException;
  3. importjava.util.List;
  4. importjavax.servlet.ServletContext;
  5. importjavax.servlet.ServletException;
  6. importjavax.servlet.annotation.WebServlet;
  7. importjavax.servlet.http.HttpServlet;
  8. importjavax.servlet.http.HttpServletRequest;
  9. importjavax.servlet.http.HttpServletResponse;
  10. importorg.apache.commons.fileupload.FileItem;
  11. importorg.apache.commons.fileupload.FileUploadException;
  12. importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
  13. importorg.apache.commons.fileupload.servlet.ServletFileUpload;
  14. importcom.alibaba.fastjson.JSONObject;
  15. /**
  16. *ServletimplementationclassFileUploadServlet
  17. */
  18. @WebServlet("/FileUploadServlet")
  19. publicclassFileUploadServletextendsHttpServlet{
  20. privatestaticfinallongserialVersionUID=1L;
  21. protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
  22. response.getWriter().println("ppppppppppppppppppp");
  23. voiddoPost(HttpServletRequestrequest,0); background-color:inherit">//需要返回的fileName
  24. StringfileName=null;
  25. //参考资料http://commons.apache.org/proper/commons-fileupload/using.html
  26. //Checkthatwehaveafileuploadrequest
  27. booleanisMultipart=ServletFileUpload.isMultipartContent(request);
  28. //Createafactoryfordisk-basedfileitems
  29. DiskFileItemFactoryfactory=newDiskFileItemFactory();
  30. //Configurearepository(toensureasecuretemplocationisused)
  31. ServletContextservletContext=this.getServletConfig().getServletContext();
  32. Filerepository=(File)servletContext.getAttribute("javax.servlet.context.tempdir");
  33. factory.setRepository(repository);
  34. //Createanewfileuploadhandler
  35. ServletFileUploadupload=newServletFileUpload(factory);
  36. //Parsetherequest
  37. try{
  38. List<FileItem>items=upload.parseRequest(request);
  39. for(FileItemitem:items){
  40. //其他参数
  41. Stringtype=item.getContentType();
  42. if(type==null){
  43. //System.out.println(item.getString(item.getFieldName()));
  44. continue;
  45. //文件参数
  46. fileName=item.getName();
  47. //设置保存文件路径
  48. StringrealPath=request.getServletContext().getRealPath("/image");
  49. Filedir=newFile(realPath);
  50. Filef=newFile(dir,fileName);
  51. if(f.exists()){
  52. f.delete();
  53. f.createNewFile();
  54. //保存
  55. item.write(f);
  56. }catch(FileUploadExceptione){
  57. e.printStackTrace();
  58. catch(Exceptione){
  59. //返回结果
  60. JSONObjectobj=newJSONObject();
  61. obj.put("fileName",fileName);
  62. response.getWriter().print(obj.toJSONString());
  63. }

需要用到的一个js文件:(点击下载)

ajaxfileupload.js

两个jar包:

commons-io-2.4.jar

commons-fileupload-1.3.1.jar


注意:上传成功之后没有执行回调函数

解决方法:(参考链接http://www.myexception.cn/ajax/727453.html

打开ajaxfileupload.js拉到底下找到

[javascript] copy
    if(type=="json"){
  1. eval("data="+data);
  2. }

改成:

copy
    data=data.replace("<pre>","").replace("</pre>","");
  1. //data=eval("("+data.replace("<pre>","").replace("</pre>","")+")");
  2. }


版权声明:本文为博主原创文章,转载请注明原地址。
kookkj 2016-10-27 11:1312楼
  • 怒赞
  • laizhiming1989 2016-01-14 12:0911楼
  • [html] view plain copy
    1. prestyle="word-wrap:break-word;white-space:pre-wrap;">


    这个怎么过滤?
  • a708856902 2016-01-13 14:5710楼
  • 抄东西都抄不全,真是醉了,你确定最后你的替换内容有效?白让我找了半天
  • 回复
    qq_32901793 2015-11-18 10:169楼
  • 能发我一份吗854580614@qq.com
  • 原文链接:https://www.f2er.com/ajax/160619.html

    猜你在找的Ajax相关文章