1. 程式人生 > >Spring Boot 整合之檔案上傳與下載

Spring Boot 整合之檔案上傳與下載

1.匯入依賴

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

2.編寫封裝類 返回資訊

public class FileInfo {

    private String path;

    public FileInfo(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}

3.編寫controller 實現檔案上傳與下載

3.1建立

@RestController
@RequestMapping("/file")
public class FileController {


    /**
     * 上傳圖片
     * @param file
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping
    public FileInfo upload(MultipartFile file,HttpServletRequest req) throws Exception {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());//原圖片名
        System.out.println(file.getSize());//大小
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //圖片名
        String fileName=file.getOriginalFilename();
        fileName=sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'));
        //路徑
        String path=req.getSession().getServletContext().getRealPath("/")+ "upload\\";
        File localFile = new File(path, fileName);

        file.transferTo(localFile);
        //返回json格式
        return new FileInfo(localFile.getAbsolutePath());
    }

    /**
     * 下載圖片
     * @param id
     * @param request
     * @param response
     */
    @GetMapping("/{id}")//id為要下載的圖片名:123.jsp
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        String path=request.getSession().getServletContext().getRealPath("/")+ "upload\\";
        try (InputStream inputStream = new FileInputStream(new File(path, id ));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + id);

            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

[email protected]和@Controller區別

@RestController註解相當於@ResponseBody + @Controller合在一起的作用。

1) 如果只是使用@RestController註解Controller,則Controller中的方法無法返回jsp頁面,或者html,配置的檢視解析器 InternalResourceViewResolver不起作用,返回的內容就是Return 裡的內容。

轉json請看https://blog.csdn.net/qq_40369944/article/details/83898752

2) 如果需要返回到指定頁面,則需要用 @Controller配合檢視解析器InternalResourceViewResolver才行。
    如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody註解。

4.測試

4.1上傳

4.1.1html:

<form action="/file" method="post"  enctype="multipart/form-data" >
        <input type="file" name="file">
        <input type="submit" value="ok">
    </form>

4.1.2頁面:

4.1.3結果:

4.2下載

我就直接根據專案中的圖片名下載

get方式    地址:

瀏覽器下載: