zoukankan      html  css  js  c++  java
  • springMVC框架下——通用接口之图片上传接口

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

    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 }

    上传图片流程如下:

    点击上传后,返回

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

  • 相关阅读:
    ImageView一例
    TextView之一:子类的常用属性
    TextView之二:常用属性
    Android中的消息机制:Handler消息传递机制
    关于LayoutParams
    LinearLayout的一些注意事项
    支付宝扫描二维码登录网站
    Cok
    Cok
    STM32的USART
  • 原文地址:https://www.cnblogs.com/lhat/p/5156327.html
Copyright © 2011-2022 走看看