使用SpringBoot实现文件上传

本篇博客使用实例说明如何使用springboot实现单文件上传、多文件上传和多文件下载,在实例中会给出前端代码后后端代码。前端代码以下:html

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  
    <head>  
        <title>DownloadAndUpload</title>  
    </head>  
    <body>  
       <form method="POST" enctype="multipart/form-data" action="http://localhost:9000/singleFileUpload">   
           <p>文件1:<input type="file" name="file" /></p>  
           <p><input type="submit" value="单文件上传" /></p>  
       </form> 
       <form method="POST" enctype="multipart/form-data" action="http://localhost:9000/multiFileUpload">   
           <p>文件1:<input type="file" name="file" /></p>  
           <p>文件2:<input type="file" name="file" /></p>  
           <p>文件3:<input type="file" name="file" /></p>  
           <p><input type="submit" value="多文件上传" /></p>  
       </form>
        <form method="GET" enctype="multipart/form-data" action="http://localhost:9000/downloadFile">   
           <p><input type="submit" value="下载文件" /></p>  
       </form>     
    </body>  
</html>

先来看看上传一个文件,本次实例中前端使用的是form表单的形式提交带上传的文件,在后端使用MultiFile接收前端提交的文件。后端代码以下:前端

@RequestMapping(value = "singleFileUpload",method = RequestMethod.POST)
    public ResponseDto singleFileUpload(@RequestParam("file")MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        File fileDir = new File("tmp");
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        String path = fileDir.getAbsolutePath();
        file.transferTo(new File(fileDir.getAbsolutePath(),fileName));
        Map<String ,String> result = new HashMap<String, String>();
        result.put("name",file.getOriginalFilename());
        result.put("size",String.valueOf(file.getSize()));
        ResponseDto dto = new ResponseDto();
        dto.setData(result);
        dto.setStatus("200");
        dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        return dto;
    }

在后台代码中指定了,form表单中文件的控件名为file,若是前端的name没有设置为file,后端将没法正确接收到文件。后端重要是经过MultiFile拿到前端传入的文件,并在代码中实现转存。web

多文件上传的后端代码以下:spring

@RequestMapping(value = "multiFileUpload",method = RequestMethod.POST)
    public ResponseDto multiFileUpload(@RequestParam("file") MultipartFile[] files){
        StringBuilder builder = new StringBuilder();
        for (MultipartFile file : files){
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
            File fileDir = new File("tmp");
            if(!fileDir.exists()){
                fileDir.mkdir();
            }
            String path = fileDir.getAbsolutePath();
            try {
                file.transferTo(new File(fileDir.getAbsolutePath(),fileName));
            } catch (IOException e) {
                continue;
            }
            builder.append(file.getOriginalFilename()).append(",");
        }

        if(builder.length()>1){
            builder = builder.deleteCharAt(builder.length()-1);
        }
        ResponseDto dto = new ResponseDto();
        dto.setData(builder.toString());
        dto.setStatus("200");
        dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        return dto;
    }

跟单文件上传的后端代码相似,只不过这里传入的参数是一个File文件数组,须要使用循环对数组里的每一个文件作转存处理。多文件上传时,前端多个文件控件的名字都要与后端中RequestParam中指定的名称的对应,不然后端只会获得一个空的文件数组。后端

关于文件下载,就是经过Response将服务器或者其余地方存储的文件,以数据流的格式返回给前端,代码以下:数组

@RequestMapping(value = "/downloadFile", method=RequestMethod.GET)
    public void downFileFromServer(HttpServletResponse response){
        String fileName = "ScrollViewGroup.avi";
        //response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File("tmp",fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

这里须要注意,在使用response返回文件时,须要指定response的内容类型,在传输文件时,设置为:application/octet-stream,在response的header中须要设置Content-Disposition,这个设置代表文件时下载仍是在线打开,不能够不设置的。springboot

上述代码实测有效,须要的朋友能够直接使用。服务器