Java檔案上傳下載

來源:互聯網
上載者:User

Java檔案上傳下載
基本原理

檔案上傳原理
通過為表單元素設定Method=”post” enctype=”multipart/form-data”屬性,讓表單提交的資料以二進位編碼的方式提交,在接收此請求的Servlet中用二進位流來擷取內容,就可以取得上傳的檔案的內容,從而實現檔案的上傳。

檔案下載原理

JSP+Servlet實現檔案上傳下載上傳

    

    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("已接收到請求");        //從request當中擷取流資訊        InputStream fileSource = req.getInputStream();        String tempFileName = "E:/tempFile";        //tempFile指向臨時檔案        File tempFile = new File(tempFileName);        //outputSteam檔案輸出資料流指向這個臨時檔案        FileOutputStream outputStream = new FileOutputStream(tempFile);        byte b[] = new byte[1024];        int n;        while((n = fileSource.read(b)) != -1){            outputStream.write(b, 0, n);        }        //關閉輸出資料流、輸入資料流        outputStream.close();        fileSource.close();        //擷取上傳的檔案的名稱        RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");        randomFile.readLine();        String str = randomFile.readLine();        int beginIndex = str.lastIndexOf("\\")+1;        int endIndex = str.lastIndexOf("\"");        String filename = str.substring(beginIndex, endIndex);        //重新置放檔案指標到檔案頭        randomFile.seek(0);        long startPostion = 0;        int i = 1;        //擷取檔案內容的開始位置        while((n = randomFile.readByte()) != -1 && i <= 4){            if(n == '\n'){                startPostion = randomFile.getFilePointer();                i++;            }        }        startPostion = startPostion - 1;        //擷取檔案內容的結束位置        randomFile.seek(randomFile.length());        long endPosition = randomFile.getFilePointer();        int j = 1;        while(endPosition >= 0 && j<=2){            endPosition--;            randomFile.seek(endPosition);            if(randomFile.readByte() == '\n'){                j++;            }        }        endPosition = endPosition - 1;        //設定儲存檔案上傳檔案的路徑        String realPath = getServletContext().getRealPath("/")+"images";        File fileupload = new File(realPath);        if(!fileupload.exists()){            fileupload.mkdir();        }        File saveFile = new File(realPath, filename);        RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile, "rw");        //從臨時檔案中讀取檔案內容(根據起止位置擷取)        randomAccessFile.seek(startPostion);        while(startPostion > endPosition){            randomAccessFile.write(randomFile.readByte());            startPostion = randomFile.getFilePointer();        }        //關閉輸入輸出資料流、刪除臨時檔案        randomAccessFile.close();        randomFile.close();        tempFile.delete();        req.setAttribute("result", "上傳成功!");        RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");        dispatcher.forward(req, resp);    }
下載

下載實現思路

text.txt
package com.imooc.servlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DownloadServlet extends HttpServlet {    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doGet(req, resp);    }    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        //擷取檔案下載路徑        String path = getServletContext().getRealPath("/")+"images/";        String filename = req.getParameter("filename");        File file = new File(path+filename);        if (file.exists()) {            //設定相應類型            resp.setContentType("application/x-msdownlaod");            //設定頭資訊            resp.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");            InputStream inputStream = new FileInputStream(file);            ServletOutputStream outputStream = resp.getOutputStream();            byte b[] = new byte[1024];            int n;            while((n = inputStream.read(b)) != -1){                outputStream.write(b, 0, n);            }            //關閉流、釋放資源            outputStream.close();            inputStream.close();        }else{            req.setAttribute("errorResult", "檔案不存在,下載失敗!");        }    }}
SmartUpload

上傳
如下上傳檔案:

    

處理過程如下:

        //設定上傳檔案儲存路徑        String filePath = getServletContext().getRealPath("/")+"images";        File file = new File(filePath);        if(!file.exists()){            file.mkdir();        }        SmartUpload su = new SmartUpload();        //初始化對象        su.initialize(getServletConfig(), request, response);        //設定上傳檔案大小        su.setMaxFileSize(1024*1024*10);        //設定所有檔案大小        su.setTotalMaxFileSize(1024*1024*100);        //設定允許使用者上傳檔案類型        su.setAllowedFilesList("txt,jpg,png,gif");        String result    = "上傳成功";        //設定禁止上傳檔案類型        try{            su.setDeniedFilesList("rar,jsp,js");            //上傳檔案            su.upload();            int count = su.save(filePath);        }catch(Exception e){            e.printStackTrace();            result = "上傳失敗";        }

異常處理

            if(e.getMessage().indexOf("1015") != -1){                result = "上傳失敗:上傳檔案類型不正確!";            }else if(e.getMessage().indexOf("1010") != -1){                result = "上傳失敗:上傳檔案類型不正確!";            }else if(e.getMessage().indexOf("1105") != -1){                result = "上傳失敗:上傳檔案大小大於允許的最大值!";            }else if(e.getMessage().indexOf("1110") != -1){                result = "上傳失敗:上傳檔案總大小大於允許的最大值!";            }

通過SmartUpload擷取上傳檔案的其他屬性

        for(int i = 0; i < su.getFiles().getCount(); i++){            org.lxh.smart.File tempFile = su.getFiles().getFile(i);            System.out.println("--------");            System.out.println("表單當中name的值:"+tempFile.getFieldName());            System.out.println("上傳檔案名稱:"+tempFile.getFileName());            System.out.println("上傳檔案的大小:"+tempFile.getSize());            System.out.println("上傳檔案的拓展名:"+tempFile.getFileExt());            System.out.println("上傳檔案的全名:"+tempFile.getFilePathName());            System.out.println("--------");        }

輸出結果如下:

表單當中name的值:myfile3上傳檔案名稱:2.png上傳檔案的大小:316681上傳檔案的拓展名:png上傳檔案的全名:2.png

下載

下載:img2-lg.jpg

SmartDownloadServlet如下:

    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String filename = req.getParameter("filename");        SmartUpload su = new SmartUpload();        su.initialize(getServletConfig(), req, resp);        su.setContentDisposition(null);        try {            su.downloadFile("/images/"+filename);        } catch (SmartUploadException e) {            e.printStackTrace();        }    }

使用SmartUpload實現檔案批量下載
如何?檔案的批量下載?

    

servlet處理

        resp.setContentType("application/x-msdownload");        resp.setHeader("Content-Disposition", "attachment;filename=test.zip");        String filepath = getServletContext().getRealPath("/")+"images/";        String[] filenames = req.getParameterValues("filename");        String str = "";        String rt = "\r\n";        ZipOutputStream zipOutputStream  = new ZipOutputStream(resp.getOutputStream());        for(String filename : filenames){            str += filename+rt;            File file = new File(filepath+filename);            zipOutputStream.putNextEntry(new ZipEntry(filename));            FileInputStream fis = new FileInputStream(file);            byte b[] = new byte[1024];            int n = 0;            while((n = fis.read(b)) != -1){                zipOutputStream.write(b, 0, n);            }            zipOutputStream.flush();            fis.close();        }        zipOutputStream.setComment("download success:"+rt+str);        zipOutputStream.flush();        zipOutputStream.close();

聯繫我們

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