通过http上传图片
1、模拟前端传递byte数组
2、将byte数组转成文件
3、发送http请求
所需要的依赖包:
<!--httpUtil-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.7</version>
<exclusions>
<exclusion>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents</groupId>
</exclusion>
</exclusions>
</dependency>
具体代码实现:
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
/**
* @version : 1.0
* @Description :
* @Date: 2023/3/17 15:26
* @Author : xhb
**/
@Slf4j
public class Httptest {
// 临时文件保存目录
private static String filePath = "/data/dataTmp/cache/test/";
// 换成你要访问的域名地址
private static String url = "https://www.baidu.com/";
public static void main(String[] args) throws IOException {
// 模拟前端传递byte数组
byte[] bytes = toByteArray("C:\\Users\\Desktop\\图片\\1.jpeg");
System.out.println(Arrays.toString(bytes));
// 将byte数组转成文件
File file = convertByteToFile(bytes, filePath);
//System.out.println(file.getName());
// 获取文件后缀
//System.out.println(file.getName().substring(file.getName().lastIndexOf(".")));
// 请求路径
String uploadUrl = url + "/uploadPicture";
// 发送http请求
createUploadHttpclient(url,new String("xxxx"),new String("01"),new String("xxxx"),file);
}
/**
* 将byte数组转为File
*
* @param bytes byte数组
* @return File文件
*/
public static File convertByteToFile(byte[] bytes, String filePath) {
if (bytes == null) {
return null;
}
BufferedOutputStream bufferedOutputStream = null;
try {
// 每次上传文件之前,需要先将之前的文件删除掉
File file = new File(filePath);
// 如果文件夹存在就不创建
if (!file.exists()) {
file.mkdirs();
}
// 只删除该文件夹下的文件,不删除文件夹
if (file.isDirectory()) {
for (File f : file.listFiles()) {
f.delete();
}
}
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "upload.png";
File fileUpload = new File(filePath + fileName);
//父级目录
File fileParent = fileUpload.getParentFile();
//判断父级目录是否存在
if (!fileParent.exists()) {
fileParent.mkdirs();
}
//创建文件
fileUpload.createNewFile();
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileUpload));
bufferedOutputStream.write(bytes);
return fileUpload;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* @return java.lang.String
* @Description : 图片上传
* @Param [orgId, pictureType, file]
**/
public static String createUploadHttpclient(String url, String orgId, String pictureType,String reqId, File file) {
CloseableHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(file);
//String reqId = UUID.randomUUID().toString().replaceAll("-", "");
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("file", bin)//文件
.addTextBody("orgId", orgId)//机构号
.addTextBody("pictureType", pictureType)//图片类型
.addTextBody("reqId", reqId).build();//请求流水
httppost.setEntity(reqEntity);
log.info("executing request:{} ", httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
log.info("response.getStatusLine:{}", response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String result = EntityUtils.toString(resEntity, "UTF-8");
JSONObject resultJson = JSONObject.parseObject(result);
if ("0000".equals(resultJson.getString("code"))) {
log.info("返回结果:{}", result);
return result;
}
} else {
log.error("上传图片异常");
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
log.error("httpClient ClientProtocolException", e);
} catch (IOException e) {
log.error("httpClient IOException", e);
} finally {
try {
httpclient.close();
} catch (IOException e) {
log.error("httpClient IOException in finally", e);
}
}
return null;
}
/**
* @Description : 读取文件以byte[]数组形式返回
* @Param [filename]
* @return byte[]
**/
public static byte[] toByteArray(String filename) throws IOException {
File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
}