java基於servlet的檔案非同步上傳_java

來源:互聯網
上載者:User

在這裡使用了基於servlet的檔案非同步上傳,好了廢話不多說,直接上代碼了。。。

package com.future.zfs.util;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;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.FileUploadBase.SizeLimitExceededException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;@SuppressWarnings("serial")public class FileUploadServlet extends HttpServlet {  final long MAX_SIZE = 10 * 1024 * 1024;// 設定上傳檔案最大為 10M  // 允許上傳的檔案格式的列表  final String[] allowtype = new String[] {"jpg","jpeg","gif","txt","doc","docx","mp3","wma","m4a","xls"};  public FileUploadServlet() {    super();  }  public void destroy() {    super.destroy();   }  @Override  protected void service(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    response.setContentType("text/html");    // 設定字元編碼為UTF-8, 這樣支援漢字顯示    response.setCharacterEncoding("UTF-8");    // 執行個體化一個硬碟檔案工廠,用來配置上傳組件ServletFileUpload    DiskFileItemFactory dfif = new DiskFileItemFactory();    dfif.setSizeThreshold(4096);// 設定上傳檔案時用於臨時存放檔案的記憶體大小,這裡是4K.多於的部分將臨時存在硬碟    dfif.setRepository(new File(request.getRealPath("/")        + "uploadtemp"));// 設定存放臨時檔案的目錄,web根目錄下的uploadtemp目錄    // 用以上工廠執行個體化上傳組件    ServletFileUpload sfu = new ServletFileUpload(dfif);    // 設定最大上傳尺寸    sfu.setSizeMax(MAX_SIZE);    PrintWriter out = response.getWriter();    // 從request得到 所有 上傳域的列表    List fileList = null;    try {      fileList = sfu.parseRequest(request);    } catch (FileUploadException e) {// 處理檔案尺寸過大異常      if (e instanceof SizeLimitExceededException) {        out.println("{message:'檔案尺寸超過規定大小:"+MAX_SIZE+"位元組'}");        return;      }      e.printStackTrace();    }    // 沒有檔案上傳    if (fileList == null || fileList.size() == 0) {      out.println("{message:'請選擇上傳檔案'}");      return;    }    // 得到所有上傳的檔案    Iterator fileItr = fileList.iterator();    // 迴圈處理所有檔案    while (fileItr.hasNext()) {      FileItem fileItem = null;      String path = null;      long size = 0;      // 得到當前檔案      fileItem = (FileItem) fileItr.next();      // 忽略簡單form欄位而不是上傳域的檔案域(<input type="text" />等)      if (fileItem == null || fileItem.isFormField()) {        continue;      }      // 得到檔案的完整路徑      path = fileItem.getName();      // 得到檔案的大小      size = fileItem.getSize();      if ("".equals(path) || size == 0) {        out.println("{message:'請選擇上傳檔案'}");        return;      }      // 得到去除路徑的檔案名稱      String t_name = path.substring(path.lastIndexOf("\\") + 1);      // 得到檔案的副檔名(無副檔名時將得到全名)      String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);      // 拒絕接受規定檔案格式之外的檔案類型      int allowFlag = 0;      int allowedExtCount = allowtype.length;      for (; allowFlag < allowedExtCount; allowFlag++) {        if (allowtype[allowFlag].equals(t_ext))          break;      }      if (allowFlag == allowedExtCount) {        String message = "";        for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++){          message+="*." + allowtype[allowFlag]                        + " ";        }        out.println("{message:'請上傳以下類型的檔案"+message+"'}");        return;      }      long now = System.currentTimeMillis();      // 根據系統時間產生上傳後儲存的檔案名稱      String prefix = String.valueOf(now);      // 儲存的最終檔案完整路徑,儲存在web根目錄下的upload目錄下      String u_name = request.getRealPath("/") + "upload/"          + prefix + "." + t_ext;      //原來的檔案名稱      path=request.getRealPath("/") + "upload/"+path;      try {        // 儲存檔案        fileItem.write(new File(path));        response.setStatus(200);        out.println("{message:\"檔案上傳成功. 已儲存為: " + prefix + "." + t_ext            + " 檔案大小: " + size + "位元組\"}");      } catch (Exception e) {        e.printStackTrace();      }    }  }}

web.xml

<servlet>    <servlet-name>fileUploadServlet</servlet-name>    <servlet-class>com.future.zfs.util.FileUploadServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>fileUploadServlet</servlet-name>    <url-pattern>/fileUploadServlet</url-pattern>  </servlet-mapping>

上傳頁面

<%@ 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>    <script type="text/javascript" src="js/jquery.js"></script>    <script type="text/javascript" src="js/ajaxfileupload.js"></script>    <script type="text/javascript">  function ajaxFileUpload()  {        $("#loading")    .ajaxStart(function(){      $(this).show();    })//開始上傳檔案時顯示一個圖片    .ajaxComplete(function(){      $(this).hide();    });//檔案上傳完成將圖片隱藏起來        $.ajaxFileUpload    (      {        url:'fileUploadServlet',//用於檔案上傳的伺服器端請求地址        secureuri:false,//一般設定為false        fileElementId:'file',//檔案上傳空間的id屬性 <input type="file" id="file" name="file" />        dataType: 'json',//傳回值類型 一般設定為json        success: function (data, status) //伺服器成功響應處理函數        {          //alert(data.message);//從伺服器返回的json中取出message中的資料,其中message為在struts2中定義的成員變數          $('#myspan').html(data.message);          if(typeof(data.error) != 'undefined')          {            if(data.error != '')            {              //alert(data.error);              $('#myspan').html(data.message);            }else            {              //alert(data.message);              $('#myspan').html(data.message);            }          }        },        error: function (data, status, e)//伺服器響應失敗處理函數        {          //alert(e);          $('#myspan').html(e);        }      }    )        return false;  }  </script>  </head>  <body>    <img src="images/loading.gif" id="loading" style="display: none;">    <span style="color: red;" id="myspan"></span><br/>    <input type="file" id="file" name="file" />    <br />    <input type="button" value="上傳" onclick="return ajaxFileUpload();">    <a href="fileDownLoadServlet?filename=通訊錄.xls">哈哈,測試檔案下載</a>  </body></html>

需要注意的是:在使用ajaxFileUpload基於servlet上傳時需要設定response.setContentType("text/html");儘管dataType: 'json'設定為json仍要設定response.setContentType("text/html");否則擷取不到伺服器端返回的資料以及會彈出一個對話方塊。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.