有时候我们会遇到根据网上的url,将图片读取但是又不想创建临时文件存到本地,尤其是在线上环境的时候,最终上传到文件服务器
我们可以将其分为几步来做
1. 根据url将其转换为输入流 利用HttpURLConnection可以将url读取成流
public static InputStream saveToFile(String destUrl){
URL url = null;
InputStream in = null;
HttpURLConnection httpUrl = null;
try{
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
in = httpUrl.getInputStream();
return in;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
- 如果我们上传的文件类型需要是MultipartFile .我们需要将流转换为MultipartFile,如果是file转File
//方法一
//转换file 但是 MockMultipartFile 是 spring-test.jar包下的,在本地可能运行成功,但是打包到线上可能失败,所以请慎重,线上环境是否能打包
MultipartFile multipartFile = null;
try {
multipartFile = new MockMultipartFile(System.currentTimeMillis()+suffix,System.currentTimeMillis()+suffix,
ContentType.APPLICATION_OCTET_STREAM.toString(),stream);
} catch (IOException e) {
e.printStackTrace();
}
/** 方法二
* 当 spring_test jar 无法打包的话可使用这个方法转换file
* @param file
* @return
*/
public MultipartFile createMultipartFile(File file) {
try {
// File转换成MutipartFile
// FileInputStream inputStream = new FileInputStream(file);
// MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
//注意这里面填啥,MultipartFile里面对应的参数就有啥,比如我只填了name,则
//MultipartFile.getName()只能拿到name参数,但是originalFilename是空。
FileItem fileItem = null;
MultipartFile multipartFile = null;
fileItem = new DiskFileItem(file.getName(), Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
InputStream input = new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(input, os);
// Or faster..
// IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
multipartFile = new CommonsMultipartFile(fileItem);
os.close();
input.close();
return multipartFile;
} catch (IOException e) {
log.error("文件转换失败" + e.getMessage());
throw new ServiceException("文件转换失败" + e.getMessage());
}
}
3.最重要的来了 ,就是实现我们的文件上传
在这里我使用的是FeignClient ,所以调用我们的方法就可以上传成功了,使用restTemplate
File tempFile = new File(url);
if(tempFile.exists()){
MultiValueMap multiValueMap = new LinkedMultiValueMap();
FileSystemResource resource = new FileSystemResource(tempFile);
multiValueMap.add("channelcode", "xxx");
multiValueMap.add("resCode", "xxx");
multiValueMap.add("files", resource);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<Map> entity = new HttpEntity<Map>(multiValueMap, headers);
String string = restTemplate.postForObject("http://199.199.199.199:9999/res/batchupload", entity, String.class);
}
ok 大功告成,喜欢的点个赞吧!!! thank you