我所想要的图片上传接口是指服务器端在完成图片上传后,返回一个可访问的图片地址

spring mvc框架下图片上传非常简单,如下 

 1 @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
 2 @ResponseBody
 3 public String uploadImg(@RequestParam(value="img")MultipartFile img){
 4     File f = new File("/data/images");
 5     try{
 6         FileUtils.copyInputStreamToFile(img.getInputStream(), f);
 7     }catch(Exception e){
 8         e.printStackTrace();
 9     }
10     return "上传成功";
11 }

非常简单吧!

1 <form action="http://localhost/component/common/uploadImg" method="post" enctype="multipart/form-data">
2     头像:<input type="file" name="img" /><br/>
3     <input type="image" src="./images/img_submit.gif" />
4 </form>

 

以上仅仅只是能够上传文件而已,而我们还要能返回一个图片地址,这个图片地址要能在浏览器中直接访问,如下:

springMVC框架下——通用接口之图片上传接口

直接代码吧!

controller层

 1 @RequestMapping(value="/uploadImg", method=RequestMethod.POST)
 2 @ResponseBody
 3 public String uploadImg(@RequestParam(value="img")MultipartFile img, HttpServletResponse response){
 4     JSONObject result = new JSONObject();
 5     boolean flag = true;
 6     try {
 7         flag = pictureUploadService.upload(img, result);
 8     } catch (Exception e) {
 9         result.put("mess", "调用失败");
10         flag = false;
11         e.printStackTrace();
12     }
13     result.put("flag", flag);
14     
15     response.setContentType("text/html;charset=UTF-8");
16     //解决跨域名访问问题
17     response.setHeader("Access-Control-Allow-Origin", "*");
18     
19     return result.toString();
20 }
View Code

相关文章:

  • 2021-12-03
  • 2022-01-08
  • 2022-01-13
  • 2021-06-17
  • 2021-09-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-10
  • 2022-02-12
  • 2021-09-27
  • 2022-02-22
  • 2021-07-04
  • 2022-01-08
  • 2021-05-26
相关资源
相似解决方案