Springboot RestTemplate 上传文件
Posted immortal_mode
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot RestTemplate 上传文件相关的知识,希望对你有一定的参考价值。
Springboot RestTemplate 上传文件
MultipartFile转File工具类
常用的工具类
import org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @description: 常用的工具
* @program: toolkit
* @author: Mikael
* @date: 2021-06-10 15:36
**/
public class CommonUtil {
//默认分隔符
private static String DELIMITER = ",";
public String getDELIMITER() {
return DELIMITER;
}
public void setDELIMITER(String DELIMITER) {
this.DELIMITER = DELIMITER;
}
/**
* 把以,分割的字符串 转化为list
* @param val 分割的字符串
* @param val 分割符
* @return List<String>
*/
public static List<String> strToList(String val){
return strToList(val,DELIMITER);
}
/**
* 自定义分割的字符串 转化为list
* @param val 分割的字符串
* @param val 分割符
* @return List<String>
*/
public static List<String> strToList(String val,String DELIMITER){
String[] values = val.split(DELIMITER);
return Arrays.asList(values);
}
/**
* List 转化为String 用指定分隔符分开 默认,
* @param list
* @return String
*/
public static String listToStr(List<String> list){
return listToStr(list,DELIMITER);
}
/**
* List 转化为String 用指定分隔符分开
* @param list
* @param DELIMITER
* @return
*/
public static String listToStr(List<String> list,String DELIMITER){
return list.stream().collect(Collectors.joining(DELIMITER));
}
/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除本地临时文件
* @param file
*/
public static void deltelTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
}
UploadController
/**
* @description: 文件上传
* @program: toolkit
* @author: Mikael
* @date: 2021-06-17 17:05
**/
@Controller
@Slf4j
@Api("文件上传控制器")
public class UploadController {
@Value("${uploadAddress}")
private String uploadAddress;
@Autowired
RestTemplate restTemplate;
@PostMapping("/upload")
@ApiOperation(value = "上传文件接口",notes = "上传文件接口")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file){
log.info("/upload POST请求 --> 进行文件上传,参数: " + file.getOriginalFilename());
Response response = new Response();
File uploadFile = null;
try {
//设置请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data");
headers.setContentType(type);
//MultipartFile转File
uploadFile = CommonUtil.multipartFileToFile(file);
//设置请求参数
FileSystemResource fileSystemResource = new FileSystemResource(uploadFile);
//设置请求体,注意是LinkedMultiValueMap
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("file", fileSystemResource);
//封装
HttpEntity<MultiValueMap<String, Object>> send = new HttpEntity<>(form, headers);
//发送
response = restTemplate.postForObject(uploadAddress, send, Response.class);
} catch (Exception e) {
e.printStackTrace();
}finally {
//删除临时文件
CommonUtil.deltelTempFile(uploadFile);
}
//这里自己封装的 根据自己业务返回就行
return response.getCode().equals(ResponseEnum.SUCCESS.getCode()) ? JSON.toJSONString(response) : (String) response.getContent();
}
}
提醒一下,应为中间进行转化的时候会生成一个临时文件,temFile在这里就表示生成的临时文件,这里只是相当于一个载体,在最后进行删除就行了
上传服务器的Controller
/**
* @description: 文件上传
* @program: fileupload
* @author: Mikael
* @date: 2021-06-17 14:09
**/
@RestController
@Slf4j
public class FileUploadController {
@Value("${uploadPath}")
private String filePath;
@Value("${addressPrefix}")
private String addressPrefix;
@PostMapping("/upload")
public Response fileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new Response("500","File is empty!");
}
String fileName = file.getOriginalFilename();
File dest = new File(filePath + fileName);
try {
if (!dest.exists()) dest.createNewFile();
file.transferTo(dest);
} catch (Exception e) {
e.printStackTrace();
return new Response("500","Upload Failed");
}
log.info("文件上传到 -->" + filePath + fileName);
log.info("公网地址 -->" + addressPrefix + fileName);
return new Response("200",addressPrefix+fileName);
}
}
以上是关于Springboot RestTemplate 上传文件的主要内容,如果未能解决你的问题,请参考以下文章
重学springboot系列番外篇之RestTemplate