1. 程式人生 > >Java 檔案上傳與下載、email

Java 檔案上傳與下載、email

/**

 * 處理檔案上傳與下載

 * @author Jie.Yuan

 *

 */

public class FileServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 獲取請求引數: 區分不同的操作型別

String method = request.getParameter("method");

if ("upload".equals(method)) {

// 上傳

upload(request,response);

}

else if ("downList".equals(method)) {

// 進入下載列表

downList(request,response);

}

else if ("down".equals(method)) {

// 下載

down(request,response);

}

}

/**

 * 1. 上傳

 */

private void upload(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

try {

// 1. 建立工廠物件

FileItemFactory factory = new DiskFileItemFactory();

// 2. 檔案上傳核心工具類

ServletFileUpload upload = new ServletFileUpload(factory);

// 設定大小限制引數

upload.setFileSizeMax(10*1024*1024); // 單個檔案大小限制

upload.setSizeMax(50*1024*1024); // 總檔案大小限制

upload.setHeaderEncoding("UTF-8"); // 對中文檔案編碼處理

// 判斷

if (upload.

isMultipartContent(request)) {

// 3. 把請求資料轉換為list集合

List<FileItem> list = upload.parseRequest(request);

// 遍歷

for (FileItem item : list){

// 判斷:普通文字資料

if (item.isFormField()){

// 獲取名稱

String name = item.getFieldName();

// 獲取值

String value = item.getString();

System.out.println(value);

}

// 檔案表單項

else {

/******** 檔案上傳 ***********/

// a. 獲取檔名稱

String name = item.getName();

// ----處理上傳檔名重名問題----

// a1. 先得到唯一標記

String id = UUID.randomUUID().toString();

// a2. 拼接檔名

name = id + "#" + name;

// b. 得到上傳目錄

String basePath = getServletContext().getRealPath("/upload");

// c. 建立要上傳的檔案物件

File file = new File(basePath,name);

// d. 上傳

item.write(file);

item.delete();  // 刪除元件執行時產生的臨時檔案

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

 * 2. 進入下載列表

 */

private void downList(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 實現思路:先獲取upload目錄下所有檔案的檔名,再儲存;跳轉到down.jsp列表展示

//1. 初始化map集合Map<包含唯一標記的檔名, 簡短檔名>  ;

Map<String,String> fileNames = new HashMap<String,String>();

//2. 獲取上傳目錄,及其下所有的檔案的檔名

String bathPath = getServletContext().getRealPath("/upload");

// 目錄

File file = new File(bathPath);

// 目錄下,所有檔名

String list[] = file.list();

// 遍歷,封裝

if (list != null && list.length > 0){

for (int i=0; i<list.length; i++){

// 全名

String fileName = list[i];

// 短名

String shortName = fileName.substring(fileName.lastIndexOf("#")+1);

// 封裝

fileNames.put(fileName, shortName);

}

}

// 3. 儲存到request

request.setAttribute("fileNames", fileNames);

// 4. 轉發

request.getRequestDispatcher("/downlist.jsp").forward(request, response);

}

/**

 *  3. 處理下載

 */

private void down(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 獲取使用者下載的檔名稱(url地址後追加資料,get)

String fileName = request.getParameter("fileName");

fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");

// 先獲取上傳目錄路徑

String basePath = getServletContext().getRealPath("/upload");

// 獲取一個檔案流

InputStream in = new FileInputStream(new File(basePath,fileName));

// 如果檔名是中文,需要進行url編碼

fileName = URLEncoder.encode(fileName, "UTF-8");

// 設定下載的響應頭

response.setHeader("content-disposition", "attachment;fileName=" + fileName);

// 獲取response位元組流

OutputStream out = response.getOutputStream();

byte[] b = new byte[1024];

int len = -1;

while ((len = in.read(b)) != -1){

out.write(b, 0, len);

}

// 關閉

out.close();

in.close();

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doGet(request, response);

}

}