SpringBootファイルのアップロードとダウンロードを実現

27767 ワード

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>Titletitle>
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 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 ;
}