SpringBoot RestTemplate接收文件,并将文件发送到另外一个程序进行存储

最近有个需求,接收用户上报的证书,并且保存起来,证书大小不到1M,但该证书的保存必须在另外一个程序进行,所以想到使用springboot接收上传文件后,再通过RestTemplate将文件发送给另外一个程序来处理,假设我们定义接收从页面中上传的文件并发送给另外一个程序的服务称之为客户端,接收客户端发送的文件的服务称之为服务端

pom依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 保存文件所需的工具类 -->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

客户端

页面

客户端使用了freemarker显示上传界面,pom文件添加依赖

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

uploadFile.ftl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
</head>
<body>
    <form name="fileForm" method="post" action="/test/upload" enctype="multipart/form-data">
            name: <input type="text" name="uploader"><br/>
            file:<input type="file", name="uploadFile">  
            <input type="submit" id = "submit">  
    </form
</body>
</html>

接收页面上传文件

package com.demo.bootdemo;

import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/test")
public class UploadFileController {

    private Logger logger = LoggerFactory.getLogger(UploadFileController.class);

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("toUploadPage")
    public String toUploadPage() {
        return "uploadFile";
    }

    @PostMapping("upload")
    @ResponseBody
    public Object upload(MultipartFile uploadFile, String uploader) {

        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpHeaders fileHeader = new HttpHeaders();
        fileHeader.setContentType(MediaType.parseMediaType(uploadFile.getContentType()));
        fileHeader.setContentDispositionFormData("uploadFile", uploadFile.getOriginalFilename());

        Map result = null;
        try {
            HttpEntity<ByteArrayResource> fileEntity = new HttpEntity<>(new ByteArrayResource(uploadFile.getBytes()),
                    fileHeader);
            multiValueMap.add("uploadFile", fileEntity);
            multiValueMap.add("uploader", uploader);

            String url = "http://127.0.0.1:8082/rest/createFile";

            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, header);
            ResponseEntity<Map> postForEntity = restTemplate.postForEntity(url, httpEntity, Map.class);
            result = postForEntity.getBody();
        } catch (Exception e) {
            logger.error("", e);
        }

        return result;

    }

}

服务器端

接收文件

package com.demo.bootdemo;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/rest")
public class CreateFileController {
    private Logger logger = LoggerFactory.getLogger(CreateFileController.class);

    @PostMapping("createFile")
    @ResponseBody
    public Map<String, Object> createFile(MultipartFile uploadFile, String uploader) {

        String message = "";
        boolean success = true;
        try {
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(),
                    new File("G:\\rest\\" + uploadFile.getOriginalFilename()));

        } catch (Exception e) {
            logger.error("", e);
            message = e.getMessage();
            success = false;
        }
        Map<String, Object> result = new HashMap<>();

        result.put("message", message);
        result.put("success", success);
        return result;

    }
}

备注

如果传递的文件过大,比如说超过了10M,则需要修改如下两个参数(单位Byte),但一般通过http上传的文件不要太大,如果太大,可以考虑使用ftp方式上传

## default 1M
spring.servlet.multipart.max-file-size=8000000000
## default 10M
spring.servlet.multipart.max-request-size=8000000000

 

posted @ 2019-10-31 09:52  大坑水滴  阅读(5965)  评论(0编辑  收藏  举报