码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-01-25 00:03:19      阅读:8526      评论:0      收藏:0      [点我收藏+]

标签:

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

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>

 

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

技术分享

直接代码吧!

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

service层

技术分享
 1 /**
 2  * 上传图片
 3  * @param file
 4  * @param params
 5  * @return
 6  * @throws Exception
 7  */
 8 public boolean upload(MultipartFile file, JSONObject params) throws Exception{
 9     //过滤合法的文件类型
10     String fileName = file.getOriginalFilename();
11     String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
12     String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico";
13     if(allowSuffixs.indexOf(suffix) == -1){
14         params.put("resultStr", "not support the file type!");
15         return false;
16     }
17     
18     //获取网络地址、本地地址头部
19     Properties config = new Properties();
20     config.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
21     String urlPath = config.getProperty("urlRoot");
22     String localPath = config.getProperty("localRoot");
23     
24     //创建新目录
25     String uri = File.separator + DateUtil.getNowDateStr(File.separator);
26     File dir = new File(localPath + uri);
27     if(!dir.exists()){
28         dir.mkdirs();
29     }
30     
31     //创建新文件
32     String newFileName = StringUtil.getUniqueFileName();
33     File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix);
34     
35     //将输入流中的数据复制到新文件
36     FileUtils.copyInputStreamToFile(file.getInputStream(), f);
37     
38     //创建Picture对象
39     Picture pic = new Picture();
40     pic.setLocalPath(f.getAbsolutePath());
41     pic.setName(f.getName());
42     pic.setUrl(urlPath + uri.replace("\\", "/") + "/" + newFileName + "." + suffix);
43     pic.setAddTime(new Date());
44     
45     //插入到数据库
46     //...
47     
48     params.put("resultStr", pic.getUrl());
49     
50     return true;
51 }
View Code

(暂时没有dao层,我在properties中配置网络地址的域名以及本地文件存储目录)

 

上传文件有几个地方需要注意:

  • 上传文件的中文乱码(这个暂不考虑,毕竟要实现的是图片上传)
  • 限制上传文件大小(文件过大,会导致服务器不堪重负),这个我们在spring mvc的配置文件中进行限制
    1 <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    2     <beans:property name="defaultEncoding" value="utf-8" />
    3     <beans:property name="maxUploadSize" value="10485760000" />
    4     <beans:property name="maxInMemorySize" value="40960" />
    5 </beans:bean>
  • 限制上传文件类型(这个我们在service层进行处理)
  • 如果一个文件夹下面保存超过1000个文件,就会影响文件访问性能,所以上传的文件要分散存储(这个分散策略有多种,不必拘泥于一种。我这里偷懒用了年月日作为目录层级
     1 /**
     2  * 获取当前日期字符串
     3  * @param separator
     4  * @return
     5  */
     6 public static String getNowDateStr(String separator){
     7     Calendar now = Calendar.getInstance();
     8     int year = now.get(Calendar.YEAR);
     9     int month = now.get(Calendar.MONTH)+1;
    10     int day = now.get(Calendar.DATE);
    11     
    12     return year + separator + month + separator + day;
    13 }
  • 上传成功后保存的文件不能重名(即文件名要唯一)
    1 //生成唯一的文件名
    2 public static String getUniqueFileName(){
    3     String str = UUID.randomUUID().toString();
    4     return str.replace("-", "");
    5 }

     

上传图片流程如下:

技术分享

点击上传后,返回

技术分享

在浏览器中输入上面的这个图片地址访问,然后出现

技术分享

 

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

标签:

原文地址:http://www.cnblogs.com/lhat/p/5156327.html

(3)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!