ext上傳組件的servlet服務端程式

來源:互聯網
上載者:User

 

package com.fh.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

public class UploadServlet extends HttpServlet {
/** *//**
*
*/
private static final long serialVersionUID = 7440302204266787092L;

String uploadPath = "d:\\uploadtest\\"; // 用於存放上傳檔案的目錄

String tempPath = "d:\\tmp\\"; // 用於存放臨時檔案的目錄

public UploadServlet() {
super();
System.out.println("檔案上傳啟動");
}

public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

public void init() throws ServletException {
System.out.println("檔案上傳初始化");
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
System.out.println("開始進行檔案上傳");
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(4194304); // 設定最大檔案尺寸,這裡是4MB
fu.setSizeThreshold(4096); // 設定緩衝區大小,這裡是4kb
fu.setRepositoryPath(tempPath); // 設定臨時目錄
List fileItems = fu.parseRequest(request); // 得到所有的檔案:
Iterator i = fileItems.iterator();
// 依次處理每一個檔案:
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();// 獲得檔案名稱,這個檔案名稱包括路徑:
if (fileName != null) {
// 在這裡可以記錄使用者和檔案資訊
// 此處應該定義一個介面(CallBack),用於處理後事。
// 寫入檔案a.txt,你也可以從fileName中提取檔案名稱:
String extfile = fileName.substring(fileName.indexOf("."));

Timestamp now = new Timestamp((new java.util.Date())
.getTime());
SimpleDateFormat fmt = new SimpleDateFormat(
"yyyyMMddHHmmssSSS");
String pfileName = fmt.format(now).toString().trim();
System.out.println(uploadPath + pfileName + extfile);
fi.write(new File(uploadPath + pfileName + extfile));
}
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("{success:true,message:'上傳成功'}");
// response.getWriter().print("{success:true,msg:'成功'}");
// 跳轉到上傳成功提示頁面
} catch (Exception e) {
e.printStackTrace();
response.getWriter().print("{success:flase,message:'失敗'}");
// 可以跳轉出錯頁面
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.