之前碰见一个需求:回调的url中的文件上传到oss上。这个变态需求对当时的我来说的确是变态。
所以,记录下:
1、将url转化成流
public MultipartFile urlToInputStream(String strUrl) {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
FileItem fileItem = createFileItem(inputStream, "合同"+System.currentTimeMillis()+".pdf");
return new CommonsMultipartFile(fileItem);
}
2、从输入流中拿到内容
public FileItem createFileItem(InputStream inputStream, String fileName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";
FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
OutputStream os = null;
//使用输出流输出输入流的字节
try {
os = item.getOutputStream();
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
inputStream.close();
} catch (IOException e) {
log.error("Stream copy exception", e);
throw new IllegalArgumentException("文件上传失败");
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("Stream close exception", e);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("Stream close exception", e);
}
}
}
return item;
}
3、将流封装
MultipartFile multipartFile = urlToInputStream(url);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
try {
ByteArrayResource byteArrayResource = new ByteArrayResource(multipartFile.getBytes()) {
@Override
public String getFilename() {
return multipartFile.getOriginalFilename();
}
};
form.add("file",byteArrayResource);
} catch (IOException e) {
log.info("byteArrayResource文件转化失败了。。。");
}
4、最后发起请求上传
HttpEntity<MultiValueMap<String, Object>> stringHttpEntity = new HttpEntity<>(form, httpHeaders);
ResponseEntity<String> response = restTemplate.postForEntity(...)
完成