檔案上傳需要用到cos.jar包。檔案上傳的顯示頁面index.jsp檔案如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>File upload</title></head><body><center><form name="upform" action="UploadServlet" method="POST" enctype="multipart/form-data"><input type="file" name="file" id="file" /><input type="submit" value="提交" /></form></center></body></html>
表單必須使用post方式提交,enctype=“multipart/form-data”這句話是必須要寫的。對應的UploadServlet.java檔案如下:
import java.io.File;import java.io.IOException;import java.util.Enumeration;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hh.excel.ExcelData;import com.oreilly.servlet.MultipartRequest;public class UploadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 上傳檔案// 檔案上傳後,儲存在C盤根目錄下request.setCharacterEncoding("utf-8");String saveDirectory = new File("c:/").getAbsolutePath();String filePath = "";// 每個檔案最大500mint maxPostSize = 1 * 500 * 1024 * 1024;// response的編碼為"utf-8",同時採用預設的檔案名稱衝突解決方案策略,實現上傳MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "utf-8");// 輸出反饋資訊Enumeration files = multi.getFileNames();while (files.hasMoreElements()) {String name = (String) files.nextElement();File f = multi.getFile(name);if (f != null) {String fileName = multi.getFilesystemName(name);filePath = saveDirectory + "\\" + fileName;System.out.println(filePath);}}}}