服务端(接受文件)
/**
* 上传文件接口
* @param type
* @return
*/
@RequestMapping(value = "/upFile",method = RequestMethod.POST)
public AjaxResult upFile(@RequestParam("type")int type,@RequestParam("file")MultipartFile file) {
System.out.println(type);
String fileName=file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String phoName=UUID.randomUUID().toString()+suffix;
/************************************************************************************/
//图片处理开始
if(file.isEmpty()){
return AjaxResult.fail("请选择文件");
}
BufferedImage bi = null;
try {
bi = ImageIO.read(file.getInputStream());
if(bi==null){
return AjaxResult.fail("您上传的不是图片格式");
}
} catch (IOException e) {
e.printStackTrace();
return AjaxResult.fail("您上传的不是图片格式");
}
File path = new File(achievement_dir);//文件保存路径
if(!path.exists()) {
path.mkdirs();
}
File f=new File(path.getAbsolutePath(),phoName);
try {
file.transferTo(f);
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.fail("文件保存异常");
}
//图片处理结束
/********************************************************************************************************/
return AjaxResult.success("success");
}
客户端(发送文件)
package com.dzqc.yx.img;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* 测试
* @author jiajia
*
*/
public class TestMain {
public static void main(String[] args) throws FileNotFoundException {
String res=httpClientUploadFile(new File("D:\\test\\a.png"));
System.out.println(res);
}
/**
* @return 响应结果
*/
public static String httpClientUploadFile(File file) {
final String remote_url = "http://localhost:8095/signup/upFile";// 第三方服务器请求地址
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
String fileName = file.getName();
HttpPost httpPost = new HttpPost(remote_url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file",new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);//文件流
builder.addTextBody("type","1");//普通字段
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;
}
}