下面提供上传的接口 适用于java代码模拟post请求 如果是html或者jsp页面的post提交则直接用注解来实现
服务端代码
@SuppressWarnings("unused")
@RequestMapping(value = "/{uid}/img/uploadAuthImg", method = {
RequestMethod.GET, RequestMethod.POST })
public String uploadAuth(@PathVariable int uid, HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
response.setContentType("text/plain;charset=utf-8");
request.setCharacterEncoding("UTF-8");
JSONObject json = new JSONObject();
try {
//未解析类提供配置信息
// DiskFileItemFactory factory = new DiskFileItemFactory();
//创建解析类的实例
//ServletFileUpload sfu = new ServletFileUpload(factory);
//设置文件的最大值,4M
//sfu.setSizeMax(1024*1024*4);
//ServletRequestContext src = new ServletRequestContext(request);
// List<FileItem> items = sfu.parseRequest(request);
// for(FileItem item : items){
// if(item.isFormField()){ //username="username"
// String name = item.getFieldName();
// String value = item.getString("utf-8");
//
// System.out.println(name + " = " + value);
// } else { //鏂囦欢
// String name = item.getName();
// item.write(new File(dir, System.currentTimeMillis() +
// name.substring(name.lastIndexOf("."))));
//
// }
//
// }
// 读取数据流 这里因为在springmvc中配置了 所以用这种方式 上面的方式不可行了
Map<String, String> param = ServletUtil.paramToMap(request);//其他的数据参数 如果是上面这种则会在name-value中取出来
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> fileList = multipartRequest.getFiles("file");
InputStream is = null;
for (MultipartFile mf : fileList) {
if (!mf.isEmpty()) {
String filename = mf.getOriginalFilename();
System.out.println(filename);
is = mf.getInputStream();
}
}
// 下面就是对springmvc中的mf进行处理 可以处理成file 也可以处理成流来存储
// 处理业务逻辑后再掉统一用户中心
// String brandList = service.uploadAuthImg(param, is);上传到fastdfs中
} catch (Exception e) {
logger.error(e);
json.put(ResultKeyConstant.DATA, "");
json.put(ResultKeyConstant.ERROR_CODE,
ErrorCodeConstant.COMMON_UNKNOWN_ERROR);// 系统内部错误
json.put(ResultKeyConstant.ERROR_MESSAGE, messageService
.getMessage(ErrorCodeConstant.COMMON_UNKNOWN_ERROR));
}
try {
PrintWriter out = response.getWriter();
out.print(json.toString());
out.close();
} catch (Exception e) {
logger.error(e);
}
return null;
}
客服端请求 用的是httpcomponents-client-4.5.2-bin.tar这个httpclient实现的
public static void main(String[] args) throws IOException {
// HttpPost httppost = new
// HttpPost("http://10.18.154.14:8080/open-web/api/upload/1234/img/uploadAuthImg2");
// "F:"+File.separator+"ds.jpg"
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(
"http://10.18.154.14:8080/open-web/api/upload/123/img/uploadAuthImg");
FileBody bin = new FileBody(new File("F:" + File.separator
+ "ds.jpg"));
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("mid", "4c8cc01a-d280-48e7-a8ae-2cef232d85bc");
paramMap.put("user_name", "测试测试");
paramMap.put("type", "jpg");
paramMap.put("identify", "430869594605632215");
StringBody param = new StringBody(JSONObject.fromObject(paramMap)
.toString(), ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("file", bin).addPart("param", param).build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String result = EntityUtils.toString(resEntity);
System.out.println(result);
}
// EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}