远程拿到其他人的图片,并根据第三方接口上传到第三方服务器上
图片地址url:可能是存储于我方数据库或用任何其他手段得到的可访问的url
第一种方式(建议的方式)不用往本方服务器存储该文件(以免浪费服务器空间),直接转换成MultipartFile对象,上传
url---->inputstream----->MultipartFile
最关键的一步是如何将 图片url转换成一个 MultipartFile对象
@Override
public String uploadCmsImage(String url) {
try {
String[] split = url.split("/");
String name = split[split.length - 1];//图片名称
// get MultipartFile
InputStream inputStream = new URL(url).openStream();
MultipartFile multipartFile = new MockMultipartFile(name, name, "", inputStream);
// build param
Map<String, MultipartFile> fileMap = new HashMap<>();
fileMap.put("file", multipartFile);
Map<String, String> map = new HashMap<>();
long time = System.currentTimeMillis() / 1000;
String sign = MD5Util.MD5(accessKey + accessSecret + time + "TESTXinHuaFouDaoSendImageSign@2018dennis.com");
map.put("time", String.valueOf(time));
map.put("sign", sign);
map.put("accessKey", accessKey);
map.put("accessSecret", accessSecret);
String res = HttpUtil.uploadFile(cmsImageUrl, fileMap, map, null);
logger.debug("upload cms image end, res:{}", res);
if (StringUtils.isNotEmpty(res)) {
JSONObject jsonObject = JSONObject.parseObject(res);
if ("200".equals(jsonObject.getString("code"))) {
return jsonObject.getJSONObject("data").getString("url");
}
return null;
}
} catch (Exception e) {
logger.error("上传图片失败:{},输入的url为{} ", e.getMessage(), url);
e.printStackTrace();
return null;
}
return null;
}
//uploadFile方法的具体实现
/**
* 使用httpclint 发送文件,如果不传输文件,直接设置fileParams=null,
* 如果不设置请求头参数,直接设置headerParams=null,就可以进行普通参数的POST请求了
*
* @param url 请求路径
* @param fileParams 文件参数
* @param otherParams 其他字符串参数
* @param headerParams 请求头参数
* @return
*/
public static String uploadFile(String url, Map<String, MultipartFile> fileParams, Map<String, String> otherParams, Map<String, String> headerParams) {
log.info("upload file url:{} param:{}", url, JSON.toJSONString(otherParams));
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
//设置请求头
if (headerParams != null && headerParams.size() > 0) {
for (Map.Entry<String, String> e : headerParams.entrySet()) {
String value = e.getValue();
String key = e.getKey();
if (StringUtils.isNotBlank(value)) {
httpPost.setHeader(key, value);
}
}
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("utf-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
// 文件传输http请求头(multipart/form-data) 自动添加
if (fileParams != null && fileParams.size() > 0) {
for (Map.Entry<String, MultipartFile> e : fileParams.entrySet()) {
String fileParamName = e.getKey();
MultipartFile file = e.getValue();
if (file != null) {
String fileName = file.getOriginalFilename();
builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
}
}
}
// 字节传输http请求头(application/json)
ContentType contentType = ContentType.create("application/json", Charset.forName("UTF-8"));
if (otherParams != null && otherParams.size() > 0) {
for (Map.Entry<String, String> e : otherParams.entrySet()) {
String value = e.getValue();
if (StringUtils.isNotBlank(value)) {
builder.addTextBody(e.getKey(), value, contentType);// 类似浏览器表单提交,对应input的name和value
}
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
第二种方式:要将图片存于服务器或本地windows电脑上
1.现根据url设置file对象的路径(这个路径是真实的可访问的路径)
// 设置File路径
public static File createFilePath(String url) {
File f2 = null;
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
// windows环境下
String prefix = "C:" + File.separator + "images" + File.separator;
// String path = systemNotice.getId() + "_" + index + File.separator;
// String path = File.separator;
String fileName = url.substring(url.lastIndexOf("/") + 1);
String suffix = fileName.trim();
// 创建文件夹
//String fileNamePath = prefix + path;
String fileNamePath = prefix;
File f1 = new File(fileNamePath);
if (!f1.exists()) {
f1.mkdirs();
}
// 创建文件
String fileAbsolutePath = fileNamePath + suffix;
f2 = new File(fileAbsolutePath);
if (!f2.exists()) {
try {
f2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
// linux环境下
String prefix = File.separator + "images" + File.separator;
//String path = systemNotice.getId() + "_" + index + File.separator;
// String path = systemNotice.getId() + "_" + index + File.separator;
String fileName = url.substring(url.lastIndexOf("/") + 1);
String suffix = fileName.trim();
// 创建文件夹
// String fileNamePath = prefix + path;
String fileNamePath = prefix;
File f1 = new File(fileNamePath);
if (!f1.exists()) {
f1.mkdirs();
}
// 创建文件
String fileAbsolutePath = fileNamePath + suffix;
f2 = new File(fileAbsolutePath);
if (!f2.exists()) {
try {
f2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return f2;
}
2.将url对应的地址的图片通过流真实的写到刚才的文件中
public static File getFileByUrl(String url, File file) {
try {
InputStream is = new URL(url).openStream();
//File file=new File()
byte[] bs = new byte[1024];
int len;
// 输出的文件流
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = new FileOutputStream(file, true);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.close();
is.close();
} catch (Exception e) {
}
return file;
}
3用带file参数的post请求 访问第三方的接口地址
/**
* 有file为参数的post请求
*
* @param url
* @param param
* @param file
* @return
* @throws IOException
*/
public static String doFilePost(String url, Map<String, String> param, File file) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String fileName = file.getName();
FileInputStream inputStream = new FileInputStream(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
for (Map.Entry<String, String> entrySet : param.entrySet()) {
String key = entrySet.getKey();
String value = entrySet.getValue();
StringBody body = new StringBody(value, ContentType.TEXT_PLAIN);
builder.addPart(key, body);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
return EntityUtils.toString(response.getEntity());
}
好,就讲到这里!
浙公网安备 33010602011771号