程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Java文件上傳下載

Java文件上傳下載

編輯:JAVA綜合教程

Java文件上傳下載


基本原理

文件上傳原理
通過為表單元素設置Method=”post” enctype=”multipart/form-data”屬性,讓表單提交的數據以二進制編碼的方式提交,在接收此請求的Servlet中用二進制流來獲取內容,就可以取得上傳的文件的內容,從而實現文件的上傳。
enctype
文件下載原理
文件下載原理

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();

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved