使用Spring进行文件的上传和下载

概览

  • 使用Spring进行文件的上传和下载
    • Spring上传文件接口设计
    • dubbo接口设计
      • 上传文件流的RPC的接口设计
    • Spring文件下载接口设计
    • dubbo接口设计
      • 下载文件流的RPC的接口设计
    • spring上传文件大小控制

使用Spring进行文件的上传和下载

本文主要介绍在Spring框架下面调用微服务的dubbo rpc接口进行文件的上传和下载,以及记录在实现过程中遇到的一些容易出错的地方。

Spring上传文件接口设计

contoller层的代码实现如下所示:

    @PostMapping("/submitEvidence")
    public BaseResponse<?> submitEvidence(@RequestParam("id") Long id, @RequestParam("label") String label,
                                          @RequestParam(value = "file") MultipartFile file) {
   
           uploadEvidence(id, label, file);
           return BaseResponse.success().errorMsg("操作成功").build();
        }
    }

使用postman请求上传文件接口,具体参数如下图所示:使用Spring进行文件的上传和下载_第1张图片
Service层代码实现如下所示:

public void uploadEvidence(Long takeDownId, String label, MultipartFile multipartFile) {
   
        if(Objects.isNull(multipartFile)) {
   
            throw new RunTimeException("上传的文件不能为空");
        }
        String fileName = multipartFile.getOriginalFilename();
        InputStream file = null;
        try {
   
            file = multipartFile.getInputStream();
        } catch (IOException e) {
   }
        byte[] fileBytes = new byte[20 * 1024 * 1024];
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
   
            outputStream =  new ByteArrayOutputStream();
            inputStream = multipartFile.getInputStream();
            try {
   
                byte[] buffer = new byte[1024];
                int read = inputStream.read(buffer);
                while (read != -1) {
   
                    outputStream.write(buffer, 0, read);
                    read = inputStream.read(buffer);
                }
            } catch (Exception e) {
   
                log.error("处理返回值失败" + e.getMessage());
                throw new RunTimeException("上传文件失败");
            } finally {
   
                try {
   
                    inputStream.close();
                } catch (IOException e) {
   
                    e.printStackTrace();
                }
            }
            outputStream.flush();
            fileBytes = outputStream.toByteArray();
        } catch (IOException e) {
   
        }finally {
   
            if(outputStream != null) {
   
                try {
   
                    outputStream.close();
                } catch (IOException e1

你可能感兴趣的:(spring,java,后端,dubbo,网络)