【SpringMvc】SpringMvc文件上传与下载

文件上传

1 前端代码

<form action="http://127.0.0.1:8080/upload" enctype="multipart/form-data" method="post">
    上传文件<input type="file" name="multipartFile"/>
    <input type="submit" value="上传"/>
</form>  

2 路径配置

server:
  port: 8080
file-path: ./appData/

3 Controller

    @Value("${file-path}")
    private String path;

    @Autowired
    HttpServletRequest request;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    private String upLoad(MultipartFile multipartFile) {
        if (multipartFile != null) {
            String originalFilename = multipartFile.getOriginalFilename();
            File filePath = new File(request.getServletContext().getRealPath(path) + File.separator + originalFilename);
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(filePath);
                return "upload success";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload failed";
    }

4 外部访问配置ResourceHandler

/**
 * @author: Curiosity
 * @Date: 2020/11/1 14:24
 * @Description:
 */
@Configuration
/**
 *  lombok为所有final 变量生成构造方法与Spring配合进行注入
 */
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
    /**
     * final 构造器注入
     */
    final ConfigurableEnvironment configurableEnvironment;
    final ServletContext servletContext;
    @Value("${file-path}")
    private String filePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取真实路径
        String realPath = servletContext.getRealPath(filePath);
        // 添加句柄 http://127.0.0.1:8080/file/git.md
        registry.addResourceHandler("/file/**")
                // 添加文件真实路径
                .addResourceLocations("file:" + realPath)
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
    }
}

文件下载

1 Controller

    @GetMapping("/down/{fileName}")
    private ResponseEntity<Resource> downLoad(@PathVariable String fileName) {
        File file = new File(request.getServletContext().getRealPath(path) + File.separator + fileName);
        if (!file.exists()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        try {
            Path path = Paths.get(file.getAbsolutePath());
            HttpHeaders headers = new HttpHeaders();
            ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            return ResponseEntity.ok()
                    .contentLength(file.length())
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity(HttpStatus.BAD_REQUEST);

    }

完整代码

1 WebConfig

@Configuration
/**
 *  lombok为所有final 变量生成构造方法与Spring配合进行注入
 */
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
    /**
     * final 构造器注入
     */
    final ConfigurableEnvironment configurableEnvironment;
    final ServletContext servletContext;
    @Value("${file-path}")
    private String filePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取真实路径
        String realPath = servletContext.getRealPath(filePath);
        // 添加句柄 http://127.0.0.1:8080/file/git.md
        registry.addResourceHandler("/file/**")
                // 添加文件真实路径
                .addResourceLocations("file:" + realPath)
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
    }
}

2 UpLoadAndDownLoadController

/**
 * @author: Curiosity
 * @Date: 2020/11/1 09:52
 * @Description:
 */
@RestController
public class UpLoadAndDownLoadController {

    @Value("${file-path}")
    private String path;

    @Autowired
    HttpServletRequest request;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    private String upLoad(MultipartFile multipartFile) {
        if (multipartFile != null) {
            String originalFilename = multipartFile.getOriginalFilename();
            File filePath = new File(request.getServletContext().getRealPath(path) + File.separator + originalFilename);
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(filePath);
                return "upload success";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "upload failed";
    }

    @GetMapping("/down/{fileName}")
    private ResponseEntity<Resource> downLoad(@PathVariable String fileName) {
        File file = new File(request.getServletContext().getRealPath(path) + File.separator + fileName);
        if (!file.exists()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        try {
            Path path = Paths.get(file.getAbsolutePath());
            HttpHeaders headers = new HttpHeaders();
            ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            return ResponseEntity.ok()
                    .contentLength(file.length())
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity(HttpStatus.BAD_REQUEST);

    }
}

3 Maven依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值