1. 程式人生 > >Smartupload 實現檔案的上傳與下載

Smartupload 實現檔案的上傳與下載

1、匯入jspSmartUpload.jar包。
2、在專案中建立上傳資料夾upload,用來儲存上傳的檔案的儲存路徑
    我的專案的結構圖如下:
這裡寫圖片描述

檔案上傳

3、編寫上傳介面。必須要設定ectype=“multipart/form-data”表示以二進位制形式提交

<form action="UpAndDownServlet" enctype="multipart/form-data" method="post">
        <input type="file" name="file"> <input type="submit" value="上傳"
> </form>

4、編寫相應的上傳servlet程式碼
(1)、建立SmartUpload物件
(2)、初始化建立的SmartUpload物件
(3)、進行檔案的上傳
(4)、把上傳的檔案儲存到伺服器上相應的資料夾,我這裡建立的是upload資料夾

@WebServlet("/UpAndDownServlet")
public class UpAndDownServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //因為檔案上傳是通過form表單提交,method為post,所以上傳操作要寫在doPost方法中
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、建立SmartUpload物件 SmartUpload smartUpload = new SmartUpload(); //2、初始化建立的SmartUpload物件 smartUpload.initialize(getServletConfig(), request, response); try
{ //3、進行檔案的上傳 smartUpload.upload(); //4、把上傳的檔案儲存到伺服器上相應的資料夾,我這裡建立的是upload資料夾 String fileSavePath = request.getServletContext().getRealPath("upload"); // 得到upload資料夾的路徑 SmartFiles files = smartUpload.getFiles(); //得到所有上傳的檔案 for (int i = 0; i < files.getCount(); i++) { //遍歷所有上傳的每一個檔案 SmartFile curFile = files.getFile(i); //得到當前上傳的檔案 //為了防止重名檔案的bug,我們這裡採用檔案上傳的時候作為檔名來儲存 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String filename = simpleDateFormat.format(new Date()); String fileExt = curFile.getFileExt(); //獲得當前檔案的字尾名 String lastFilePath = fileSavePath + "/" + filename + "." + curFile; //當前檔案的儲存路徑 curFile.saveAs(lastFilePath); } } catch (SmartUploadException e) { e.printStackTrace(); } } }

檔案下載

3、編寫下載的jsp介面

<a href="UpAndDownServlet?down=1.png">1.png</a>

4、編寫檔案下載對應的servlet程式碼

//因為下載視通過<a>標籤連結的,所以採用的是doGet方法。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //1、建立SmartUpload物件
    SmartUpload smartUpload = new SmartUpload();

    //2、初始化建立的SmartUpload物件
    smartUpload.initialize(getServletConfig(), req, resp);

    //3、檔案下載(同時需要得到檔案的下載路徑。通過 下載的jsp頁面的a連線的URL?後面的引數獲得對應的檔名)
    String filename = req.getParameter("down");         //獲得要下載的檔名
    String fileSavePath = req.getServletContext().getRealPath("upload");    //因為檔案是儲存在伺服器的upload資料夾中的,所以要獲得資料夾的路徑
    String lastDownPath = fileSavePath + "/" + filename;    //得到檔案下載的最終路徑
    try {
        smartUpload.downloadFile(lastDownPath);             //進行下載
    } catch (SmartUploadException e) {
        e.printStackTrace();
    }

}