springBoot實現文件上傳與下載


1. 文件下載

准備一個文件C:/Users/admin/Desktop/test.xlsx

 /**
     * 定制分析下載模板文檔
     * @param response
     * @return
     */
    @RequestMapping("/downLoadTemplateExcel")
    public Info downLoadTemplateExcel(HttpServletResponse response){
        logger.info("/customAnalysisConfig/downLoadTemplateExcel");
        Info infos=new Info();
        // 創建輸入輸出流
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        //String url = "C:/Users/admin/Desktop/test.xlsx";
        String url =null;
        if(environment.equals("local")){//本地文件路徑
            url ="C:/Users/admin/Desktop/test.xlsx";
        }else {//服務器文件路徑
            url = "/usr/java/test.xlsx";
        }
        String downLoadPath = url;
        String fileName="template.xlsx";//生成的文件名
        File file2 = new File(downLoadPath);//要下載的文件對象
        if (!file2.exists()) {//如果目錄不存在,創建目錄
            file2.mkdirs();
        }
        long fileLength = file2.length();// 獲取文件長度
        try {
            //Content-Disposition: attachment; filename="filename.xls"
            //第一個參數是attachment(意味着消息體應該被下載到本地;大多數瀏覽器會呈現一個“保存為”的對話框,
            // 將filename的值預填為下載后的文件名,假如它存在的話)
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            //Content-Type 實體頭部用於指示資源的MIME類型 media type
            response.setHeader("Content-Type", "application/json");
            //Content-Length, HTTP消息長度, 用十進制數字表示的八位字節的數目
            response.setHeader("Content-Length", String.valueOf(fileLength));
            // 創建輸入輸出流實例
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            // 創建字節緩沖大小
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null)
                try {
                    bis.close();// 關閉輸入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();// 關閉輸出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        infos.setCode("1");
        infos.setMsg("成功");
        return infos ;
    }

2. 單文件上傳

准備一個upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:4000/pdClientManagerSystem/customAnalysisConfig/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" value="Select your file: ">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

注意這里的 name="file"

//單文件上傳的功能
    @RequestMapping(value = "/upload")
    public String upload(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "file is empty";
            }
            String fileName = file.getOriginalFilename();//獲取文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));//切割文件名
            log.info("上傳的文件名為:" + fileName + " 后綴名為" + suffixName);
            // 設置文件存儲路徑(D盤),你可以存放在你想要指定的路徑里面。
            String filePath = "D:/upload";
            //文件存放路徑=filePath+/+ fileName
            String path = filePath + "/" + fileName;
            File dest = new File(path);
            // 檢測是否存在目錄
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夾
            }
            file.transferTo(dest);// 文件寫入到上述的存放路徑path
            return "upload success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "upload failure";
    }

3. 多文件上傳

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>批量文件上傳</title>
</head>
<body>
<form method="post" action="/batch" enctype="multipart/form-data">
<input type="file" name="file"><br> <input type="file" name="file"><br> <input type="file" name="file"><br> <br> <input type="submit" value="提交"> </form> </body> </html>

java代碼

//多文件上傳的功能
    @RequestMapping("/batch")
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String filePath = "D:/uploads";
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath  + "/" + file.getOriginalFilename())));
                    stream.write(bytes);// 寫入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "the " + i + " file upload failure";
                }
            } else {
                return "the " + i + " file is empty";
            }
        }
        return "upload Multifile success";
    }

 

 

/**
* 定制分析下載模板文檔
* @param response
* @return
*/
@RequestMapping("/downLoadTemplateExcel")
public Info downLoadTemplateExcel(HttpServletResponse response){
logger.info("/customAnalysisConfig/downLoadTemplateExcel");
Info infos=new Info();
// 創建輸入輸出流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//String url = "C:/Users/admin/Desktop/test.xlsx";
String url =null;
if(environment.equals("local")){//本地文件路徑
url ="C:/Users/admin/Desktop/test.xlsx";
}else {//服務器文件路徑
url = "/usr/java/test.xlsx";
}
String downLoadPath = url;
String fileName="template.xlsx";//生成的文件名
File file2 = new File(downLoadPath);//要下載的文件對象
if (!file2.exists()) {//如果目錄不存在,創建目錄
file2.mkdirs();
}
long fileLength = file2.length();// 獲取文件長度
try {
//Content-Disposition: attachment; filename="filename.xls"
//第一個參數是attachment(意味着消息體應該被下載到本地;大多數瀏覽器會呈現一個保存為的對話框,
// filename的值預填為下載后的文件名,假如它存在的話)
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
//Content-Type 實體頭部用於指示資源的MIME類型 media type
response.setHeader("Content-Type", "application/json");
//Content-Length, HTTP消息長度, 用十進制數字表示的八位字節的數目
response.setHeader("Content-Length", String.valueOf(fileLength));
// 創建輸入輸出流實例
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
// 創建字節緩沖大小
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (bis != null)
try {
bis.close();// 關閉輸入流
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();// 關閉輸出流
} catch (IOException e) {
e.printStackTrace();
}
}
infos.setCode("1");
infos.setMsg("成功");
return infos ;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM