spring-mvc提供上传图片接口

本文介绍了一个使用Java实现的文件上传接口,该接口通过Spring MVC框架处理HTTP POST请求,并详细展示了如何解析请求中的文件及参数,同时提供了客户端使用HttpClient发起POST请求的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面提供上传的接口 适用于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();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值