>  기사  >  php教程  >  ajaxFileUpload 비동기 파일 업로드 사용이 간편함

ajaxFileUpload 비동기 파일 업로드 사용이 간편함

高洛峰
高洛峰원래의
2016-12-12 17:33:371117검색

<%@ 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>
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 파일 1개 필요: (다운로드하려면 클릭)

ajaxfileupload.js

jar 패키지 2개:

commons-io -2.4.jar

commons-fileupload-1.3.1.jar


참고: 업로드 콜백 기능이 성공한 후에는 실행되지 않습니다.

ajaxfileupload.js를 열고 아래로 스크롤하여

if ( type == "json" ) {  
            eval( "data = " + data );  
        }

을 찾습니다.

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


으로 변경합니다.
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.