Rumah > php教程 > PHP开发 > ajaxFileUpload 异步上传文件简单使用

ajaxFileUpload 异步上传文件简单使用

高洛峰
Lepaskan: 2016-12-12 17:33:37
asal
1127 orang telah melayarinya

<%@ 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(&#39;click&#39;, function() {  
        $(&#39;#fileToUpload&#39;).click();  
    });  
      
    //选择文件之后执行上传  
    $(&#39;#fileToUpload&#39;).on(&#39;change&#39;, function() {  
        $.ajaxFileUpload({  
            url:&#39;../FileUploadServlet&#39;,  
            secureuri:false,  
            fileElementId:&#39;fileToUpload&#39;,//file标签的id  
            dataType: &#39;json&#39;,//返回数据的类型  
            data:{name:&#39;logan&#39;},//一同上传的数据  
            success: function (data, status) {  
                //把图片替换  
                var obj = jQuery.parseJSON(data);  
                $("#upload").attr("src", "../image/"+obj.fileName);  
      
                if(typeof(data.error) != &#39;undefined&#39;) {  
                    if(data.error != &#39;&#39;) {  
                        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>
Salin selepas log masuk
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());  
    }  
  
}
Salin selepas log masuk

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

ajaxfileupload.js

两个jar包:

commons-io-2.4.jar

commons-fileupload-1.3.1.jar


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

打开ajaxfileupload.js拉到底下找到

if ( type == "json" ) {  
            eval( "data = " + data );  
        }
Salin selepas log masuk

改成:

if ( type == "json" ) {  
            data = data.replace("<pre class="brush:php;toolbar:false">","").replace("
",""); //data = eval("("+data.replace("
","").replace("
","")+")"); }
Salin selepas log masuk


Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan