SpringMVC图片上传和下载

@Controller
public class FileUploadController {

    private SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    /**
     * SpringMVC 将上传的文件对象封装成一个 MultipartFile 对象,无论我们使用的是新版还是旧版的文件上传方案,这个接口中的代码都是一样的
     *
     * @param file
     * @param username
     * @return
     */
    //图片上传
    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(MultipartFile file, String username) {
        System.out.println("username = " + username);
        String folderPath = new File("D:\\img") + sdf.format(new Date());
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //获取原始的文件名
        String oldName = file.getOriginalFilename();
        //获取上传文件的后缀
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        //生成新的文件名
        String newName = UUID.randomUUID().toString() + suffix;
        try {
            file.transferTo(new File(folder, newName));
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";

    }

    //图片下载
    @GetMapping("/views/{year}/{month}/{day}/{imageName}")
    @ResponseBody
    public ResponseEntity downloadImg(@PathVariable String imageName,@PathVariable String year,@PathVariable String month,@PathVariable String day) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\img\\" + year + "\\" + month + "\\" + day + "\\" + imageName);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fis.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.IMAGE_JPEG);
        header.setContentDispositionFormData("attachment", new String(imageName.getBytes("UTF-8"), "ISO-8859-1"));
        return new ResponseEntity<>(baos.toByteArray(), header, HttpStatus.CREATED);
    }
}

你可能感兴趣的:(SpringMVC,spring)