jQuery插件之ajaxFileUpload使用小结
一、ajaxFileUpload是一个异步上传文件的jQuery插件。
传一个不知道什么版本的上来,以后不用到处找了。
语法:$.ajaxFileUpload([options])
options参数说明:
1、url 上传处理程序地址。
2,fileElementId 需要上传的文件域的ID,即<input type="file">的ID。
3,secureuri 是否启用安全提交,默认为false。
4,dataType 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success 提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error 提交失败自动执行的处理函数。
7,data 自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8, type 当要提交自定义参数时,这个参数要设置成post
错误提示:
1,SyntaxError: missing ; before statement错误
如果出现这个错误就需要检查url路径是否可以访问
2,SyntaxError: syntax error错误
如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
3,SyntaxError: invalid property id错误
如果出现这个错误就需要检查文本域属性ID是否存在
4,SyntaxError: missing } in XML expression错误
如果出现这个错误就需要检查文件name是否一致或不存在
5,其它自定义错误
大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。
使用方法:
第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。
<script src="jquery-1.7.1.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script>
第二步:HTML代码:
<body> <p><input type="file" id="file1" name="file" /></p> <input type="button" value="上传" /> <p><img id="img1" alt="上传成功啦" src="" /></p> </body>
第三步:JS代码
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <!-- 引用jquery -->
- <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
- <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
- <!-- 引用ajaxfileupload.js -->
- <script src="../js/ajaxfileupload.js"></script>
- <script type="text/javascript">
- $(function(){
- //点击打开文件选择器
- $("#upload").on('click', function() {
- $('#fileToUpload').click();
- });
- //选择文件之后执行上传
- $('#fileToUpload').on('change', function() {
- $.ajaxFileUpload({
- url:'../FileUploadServlet',
- secureuri:false,
- fileElementId:'fileToUpload',//file标签的id
- dataType: 'json',//返回数据的类型
- data:{name:'logan'},//一同上传的数据
- success: function (data, status) {
- //把图片替换
- var obj = jQuery.parseJSON(data);
- $("#upload").attr("src", "../image/"+obj.fileName);
- if(typeof(data.error) != 'undefined') {
- if(data.error != '') {
- alert(data.error);
- } else {
- alert(data.msg);
- }
- }
- },
- error: function (data, status, e) {
- alert(e);
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <!-- 点击图片,打开文件选择器,确定,上传。(这是网络上的一个图片) -->
- <img id="upload" alt="" style="width: 200px; height: 200px"
- 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标签 -->
- <input id="fileToUpload" style="display: none" type="file" name="upfile"><br/>
- </body>
- </html>
- package com.yangshidesign.weixinface.servlet;
- import java.io.File;
- import java.io.IOException;
- import java.util.List;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- import com.alibaba.fastjson.JSONObject;
- /**
- * Servlet implementation class FileUploadServlet
- */
- @WebServlet("/FileUploadServlet")
- public class FileUploadServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.getWriter().println("ppppppppppppppppppp");
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //需要返回的fileName
- String fileName = null;
- //参考资料 http://commons.apache.org/proper/commons-fileupload/using.html
- // Check that we have a file upload request
- boolean isMultipart = ServletFileUpload.isMultipartContent(request);
- // Create a factory for disk-based file items
- DiskFileItemFactory factory = new DiskFileItemFactory();
- // Configure a repository (to ensure a secure temp location is used)
- ServletContext servletContext = this.getServletConfig().getServletContext();
- File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
- factory.setRepository(repository);
- // Create a new file upload handler
- ServletFileUpload upload = new ServletFileUpload(factory);
- // Parse the request
- try {
- List<FileItem> items = upload.parseRequest(request);
- for(FileItem item : items) {
- //其他参数
- String type = item.getContentType();
- if(type == null) {
- // System.out.println(item.getString(item.getFieldName()));
- continue;
- }
- //文件参数
- fileName = item.getName();
- //设置保存文件路径
- String realPath = request.getServletContext().getRealPath("/image");
- File dir = new File(realPath);
- File f = new File(dir, fileName);
- if(f.exists()) {
- f.delete();
- }
- f.createNewFile();
- //保存
- item.write(f);
- }
- } catch (FileUploadException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- //返回结果
- JSONObject obj = new JSONObject();
- obj.put("fileName", fileName);
- response.getWriter().print(obj.toJSONString());
- }
- }
需要用到的一个js文件:(点击下载)
两个jar包:
注意:上传成功之后没有执行回调函数。
解决方法:(参考链接:http://www.myexception.cn/ajax/727453.html)
打开ajaxfileupload.js拉到底下找到
- if ( type == "json" ) {
- eval( "data = " + data );
- }
改成:
- if ( type == "json" ) {
- data = data.replace("<pre>","").replace("</pre>","");
- //data = eval("("+data.replace("<pre>","").replace("</pre>","")+")");
- }