Heim  >  Artikel  >  php教程  >  AjaxFileUpload: Asynchroner Datei-Upload, einfach zu verwenden

AjaxFileUpload: Asynchroner Datei-Upload, einfach zu verwenden

高洛峰
高洛峰Original
2016-12-12 17:33:371116Durchsuche

<%@ 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());  
    }  
  
}

Eine js-Datei benötigt: (zum Herunterladen klicken)

ajaxfileupload.js

Zwei JAR-Pakete:

commons-io -2.4.jar

commons-fileupload-1.3.1.jar


Hinweis: Keine Ausführung nach erfolgreicher Upload-Callback-Funktion.

Öffnen Sie ajaxfileupload.js und scrollen Sie nach unten, um

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

zu finden. Ändern Sie es in:

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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:jQuery-Plug-in ajaxFileUploadNächster Artikel:jQuery-Plug-in ajaxFileUpload