目录
本地客户端代码:获取图片base64编码使用httpclient 执行post
服务端代码:
记录一下java 本地代码 通过 httpclient 传递 图片 base64 编码 到服务器,然后服务器 储存图片 的一个小demo。
本地客户端代码:
获取图片base64编码
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
public static String getImageBase64(String imgFilePath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
使用httpclient 执行post
maven中引入httpclient包
org.apache.httpcomponents
httpclient
4.5.2
org.apache.httpcomponents
httpcore
4.4.6
public static void HttpClientPost(String url,List list) throws Exception {
// 获取默认的请求客户端
CloseableHttpClient client = HttpClients.createDefault();
// 通过HttpPost来发送post请求
HttpPost httpPost = new HttpPost(url);
// 我们发现Entity是一个接口,所以只能找实现类,发现实现类又需要一个集合,集合的泛型是NameValuePair类型
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
// 通过setEntity 将我们的entity对象传递过去
httpPost.setEntity(formEntity);
// 通过client来执行请求,
CloseableHttpResponse response = client.execute(httpPost);
//下面是获取响应
// HttpEntity entity = response.getEntity();
// String str = EntityUtils.toString(entity, "UTF-8");
// System.out.println(str);
response.close();
}
最后。定义方法,调用httpost 。然后指定3个参数,1个访问地址
type 访问类型filename 自定义文件名base64str 编码http://localhost/api 访问地址
public static void send(){
System.out.println("发送图片请求");
// post带参数
List list = new ArrayList();
BasicNameValuePair b = new BasicNameValuePair("type", "uploadimg");
BasicNameValuePair b2 = new BasicNameValuePair("filename", "kl.jpg");
BasicNameValuePair b3 = new BasicNameValuePair("base64str", getImageBase64("C:\\Users\\ASUS\\Desktop\\kl.jpg"));
list.add(b);
list.add(b2);
list.add(b3);
try {
HttpClientPost("http://localhost/api",list);
} catch (Exception e) {
e.printStackTrace();
}
}
服务端代码:
获取requst 中的参数,然后保存图片
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200727110805758.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMxMjU0NDg5,size_16,color_FFFFFF,t_70)
@WebServlet(name = "api" ,urlPatterns="/api")
public class apitest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type = request.getParameter("type");
if(type!=null &&type.equals("uploadimg")) {
String filename = request.getParameter("filename");
String base64str = request.getParameter("base64str");
saveImg("D://img/"+filename,base64str);
}
}
public void saveImg(String url,String base64_Str){
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(base64_Str);
for (int i = 0; i |