天天看點

java實作檔案上傳下載下傳

喜歡的朋友可以關注下,粉絲也缺。

今天發現已經有很久沒有給大家分享一篇技術文章了,于是想了一下給大家分享一篇java實作檔案上傳下載下傳功能的文章,不喜歡的希望大家勿噴。

    想必大家都知道檔案的上傳前端頁面是需要用表單來送出,下面我就直接貼代碼:

<div style="margin-bottom:5px" id="wjid">
            <form action="/automaticffice/SmartUploadServlet" method="post"  
		        enctype="multipart/form-data">  
		        <input id="filename" name="filename" type="file"  
		             /> <input type="submit" class="easyui-linkbutton" icon="icon-ok" value="提 交" /><span style="color: red">${message}</span>
		    </form>  
</div>           

    下面我們來說說背景的代碼應該怎麼寫,這裡我是用了 jspSmartUpload.jar 這個包,使用非常的友善,這裡我提供一個下載下傳位址給大家

https://download.csdn.net/download/dsn727455218/10422388

    還是直接上代碼:

@WebServlet("/SmartUploadServlet")
public class SmartUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection conn;
    private PreparedStatement pst;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 設定上傳的儲存路徑
        String filePath = getServletContext().getRealPath("/") + "\\upload\\";
        System.err.println(filePath);
        // 建立檔案對象 如果存在就不建立,否則建立檔案夾
        File file = new File(filePath);
        if (file.exists()) {
            file.mkdir();
        }
        // 建立SmartUpload對象
        SmartUpload su = new SmartUpload();
        // 初始化對象
        su.initialize(getServletConfig(), request, response);
        // 設定上傳檔案大小
        su.setTotalMaxFileSize(1024 * 1024 * 100);
        // 設定上傳檔案類型
        //        su.setAllowedFilesList("txt,jpg,gif,xls,doc,docx");
        // 建立提示變量
        String result = "上傳成功";
        try {
            // 設定禁止上傳類型
            //            su.setDeniedFilesList("rar,jsp,js");
            su.upload();
            // 傳回上傳檔案數量
            int count = su.save(filePath);
            System.out.println("上傳成功" + count + "個檔案!");

        } catch (Exception e) {
            result = "上傳失敗";
            e.printStackTrace();
        }

        // 擷取上傳成功的檔案的屬性
        for (int i = 0; i < su.getFiles().getCount(); i++) {
            com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
            System.out.println("---------------------");
            System.out.println("表單當中name屬性值:" + tempFile.getFieldName());
            System.out.println("上傳檔案名:" + tempFile.getFieldName());
            System.out.println("上傳檔案長度:" + tempFile.getSize());
            System.out.println("上傳檔案的拓展名:" + tempFile.getFileExt());
            System.out.println("上傳檔案的全名:" + tempFile.getFilePathName());
            System.out.println("---------------------");
          
        }
        request.setAttribute("message", result);

        RequestDispatcher dispatcher = request.getRequestDispatcher("do/wenjian.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}           

其實上傳檔案就是這麼的簡單,下面我們來說說檔案的下載下傳,相信很多的朋友有遇到過檔案名字為中文的檔案就無法下載下傳的問題,接下來我們就詳細的來說下這個問題:

同樣的前端還是要以表單的方式送出:

input裡面value的值是你需要下載下傳檔案的名字,action都知道是servetl的路徑了

<form action="/automaticffice/BatchDownloadServlet"> <input type="hidden" name="filename" value="' + cellvalue + '"/> <input type="submit" value="下載下傳檔案"/></form>           

在servlet中如何接收處理:

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("filename");
        /**
         * 這裡是重點,如何解決檔案名為中文的問題,不同的浏覽器處理的方式會有所不同
         * IE的話,通過URLEncoder對filename進行UTF8編碼,
         * 而其他的浏覽器(firefox、chrome、safari、opera),則要通過位元組轉換成ISO8859-1了
         * 是以這裡我們需要判斷一下使用的是什麼浏覽器 在根據浏覽器來做相應的編碼
         */
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            name = URLEncoder.encode(name, "UTF-8");
        } else {
            name = new String(name.getBytes(), "ISO-8859-1");
        }
        response.setContentType("application/octet-stream");
        // 以附件的形式下載下傳
        response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");

        // 擷取下載下傳路徑
        String path = getServletContext().getRealPath("/") + "\\upload\\";
        // 擷取檔案數組
        String[] filenames = request.getParameterValues("filename");
        // 建立空字元串
        String str = "";
        // 換行符
        String rt = "\r\n";
        // 建立壓縮包輸出流
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        // 周遊檔案數組
        for (String filename : filenames) {
            str += filename + rt;
            // 建立檔案對象
            File file = new File(path + filename);
            zos.putNextEntry(new ZipEntry(filename));
            // 建立檔案輸出流
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n = 0;
            while ((n = fis.read(b)) != -1) {
                zos.write(b, 0, n);
            }
            zos.flush();
            fis.close();
        }
        zos.setComment("成功" + rt + str);
        zos.flush();
        zos.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}           

到這裡已經完成了對檔案的上傳下載下傳功能,如有需要可以加我Q群【308742428】大家一起讨論技術

下一篇我将繼續為大家分享 如何實作檔案的線上預覽功能,希望大家期待