package com.seven.micropay.channel.service.adapter.merRegist;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.seven.micropay.channel.util.ImageUploadSSLContextUtils;
import com.seven.micropay.channel.util.ImageUploadSignUtilss;
import com.seven.micropay.commons.config.properties.Property;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* ClassName: AlipayHandlerAdapter Description: 微信扫码付适配 date: 2019年11月08日
* 下午17:33:21 图片上传接口
*
* @author GW
* @version 1.0
*
*/
@Service
public class ImageUploadutil{
public Logger log = LoggerFactory.getLogger(this.getClass());
public String uploadFile(MultipartFile multipartFile) {
String uploadUrl=Property.getProperty("upload.Url");
String p12Url=Property.getProperty("p12Url");
HttpPost httpPost = new HttpPost(uploadUrl);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.MULTIPART_FORM_DATA.getMimeType());
CloseableHttpClient client = null;
File excelFile = null;
String error = null;
String mch_id=Property.getProperty("weixin.pay.cert_password");
String HMAC_SHA256=Property.getProperty("sign_type");
String tradeMerKey=Property.getProperty("weixin.pay.provider.key");
try {
client = HttpClients.custom()
.setSSLContext(
ImageUploadSSLContextUtils.getSSLContext(p12Url, mch_id))
.build();
// 生成签名和图片md5加密
String hash = DigestUtils.md5Hex(multipartFile.getBytes());
Map
param.put("media_hash", hash);
param.put("mch_id", mch_id);
param.put("sign_type", HMAC_SHA256);
// 配置post图片上传
// 用uuid作为文件名,防止生成的临时文件重复
excelFile = File.createTempFile(UUID.randomUUID().toString(), ".jpg");
multipartFile.transferTo(excelFile);
FileBody bin = new FileBody(excelFile, ContentType.create("image/jpg", Consts.UTF_8));
HttpEntity build = MultipartEntityBuilder.create().setCharset(Charset.forName("utf-8"))
.addTextBody("media_hash", hash).addTextBody("mch_id", mch_id)
.addTextBody("sign_type", HMAC_SHA256)
.addTextBody("sign", ImageUploadSignUtilss.wechatCertficatesSignBySHA256(param, tradeMerKey))
.addPart("media", bin).build();
httpPost.setEntity(build);
HttpResponse httpResponse = client.execute(httpPost);
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
String responseEntity = EntityUtils.toString(httpResponse.getEntity());
log.info("upload response {}", responseEntity);
Document document = DocumentHelper.parseText(responseEntity);
if ("SUCCESS".equalsIgnoreCase(document.selectSingleNode("//return_code").getStringValue())) {
if ("SUCCESS".equalsIgnoreCase(document.selectSingleNode("//result_code").getStringValue())) {
return document.selectSingleNode("//media_id").getStringValue();
}
}
log.error("上传图片失败,异常信息 code ={} des = {}", document.selectSingleNode("//err_code").getStringValue(),
document.selectSingleNode("//err_code_de").getStringValue());
error = document.selectSingleNode("//err_code_de").getStringValue();
}
} catch (Exception e) {
log.error("微信图片上传异常 , e={}", e);
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
log.warn("关闭资源httpclient失败 {}", e);
}
}
if (excelFile != null) {
deleteFile(excelFile);
}
}
return error;
}
/**
* 删除临时文件
*
* @param files
*/
private void deleteFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
public static String Println(File savePath, ImageUploadutil up) {
String fileName = "";
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
FileItem item = factory.createItem(textFieldName, "text/plain", true, fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(savePath + fileName);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
MultipartFile multipartFile = new CommonsMultipartFile(item);
System.out.println(multipartFile.getName());
String mults = up.uploadFile(multipartFile);
System.out.println(mults);
return mults;
}
}