• 关于图片上传工具类编写


     1 package obj.controller;
     2 import java.io.File;
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 import java.util.UUID;
     6 import javax.servlet.http.HttpServletRequest;
     7 import org.springframework.web.multipart.MultipartFile;
     8 
     9 public class upload2 {
    10    public List<String> uploadfile(HttpServletRequest request, MultipartFile[] files) {
    11       //返回所有上传成功的图片路径集合
    12       List<String> list = new ArrayList<String>();
    13 
    14       // 图片存放路径,将上传文件保存在tomcat服务器路径下
    15       String savePath = request.getServletContext().getRealPath("/serverimg");
    16       System.out.println(savePath);
    17 //F:eclipseworkspace.metadata.pluginsorg.eclipse.wst.server.core	mp1wtpwebappsspringmvcserverimg
    18 
    19       File file = new File(savePath);
    20       // 如果目录不存在
    21       if (!file.exists()) {
    22          // 创建目录
    23          file.mkdirs();
    24       }
    25 
    26       if (files != null && files.length > 0) {
    27          for (int i = 0; i < files.length; i++) {
    28             // 得到上传的文件名字
    29             String imgname = files[i].getOriginalFilename();
    30             if (imgname!=null && imgname!="") {
    31                // 得到上传文件的扩展名
    32                String fileExtName = imgname.substring(imgname.lastIndexOf("."));
    33                // 保存的文件名生成uuid
    34                String filename = makeFileName(fileExtName);
    35                // 图片存放路径
    36                String filePath = savePath + "/" + filename;
    37 
    38                // 访问图片路径,往数据库里放直接可以显示图片的路径
    39                //String basePath = "http://localhost:8080"+request.getContextPath()+"/serverimg/";
    40                //String path = basePath + "/" + filename;
    41                // 访问图片路径,往数据库里放上传后的图片名字,路径需要前台自已写
    42                String path = filename;
    43 
    44                File saveDir = new File(filePath);
    45                if (!saveDir.getParentFile().exists()) {
    46                  saveDir.getParentFile().mkdirs();
    47                }
    48 
    49                // 转存文件
    50                try {
    51                  files[i].transferTo(saveDir);
    52                } catch (Exception e) {
    53                  // TODO Auto-generated catch block
    54                  e.printStackTrace();
    55                }
    56                list.add(path);
    57             }
    58          }
    59       }
    60       return list;
    61    }
    62 
    63    private String makeFileName(String fileExtName) {
    64       // 为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
    65       return UUID.randomUUID().toString().replace("-", "") + fileExtName;
    66    }
    67 
    68 }
    69  

    前台页面的编写

    $(document).ready(function(){  
    $('.jtt').get(0).onchange=function (e){
           var that=this;
           console.dir(this)
           var read=new FileReader();
           read.readAsDataURL(this.files[0]);
           console.log($('.sh2').get(0).src)
           read.onload=function () {
               $('.sh2').get(0).src=this.result;
           }  
           
           var formData = new FormData($("#form")[0]);
    
           
           $.ajax({
              url : '<%= request.getContextPath()%>/banner/img',
              type : "POST",
              data : formData,
              dataType : "json",
              processData : false, //必须false才会避开jQuery对 formdata 的默认处理
              contentType : false, //必须false才会自动加上正确的Content-Type
              cache : false, //true的话会读缓存
              success : function(data) {
                  console.log(data);
                $.each(data,function(i,obj){
                    console.log(obj)
                    $("#form").append('<input type="text" name="banner" value="'+(obj)+'">');
                })
              }
           });
           
       }
    })

    依赖jar包

    <!-- jsp依赖必须引入,不然访问jsp页面会另存为 -->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>provided</scope>
            </dependency>
  • 相关阅读:
    Sql ISNULL() 函数
    C#WinForm中按钮响应回车事件的简单方法
    职场升迁全攻略 人脉资源是铺垫
    怎样成为有钱人
    睡前应做六件事
    赚钱的秘诀(转)
    将Win2003转换成个人PC版系统
    抠图神器Inpaint 4.2
    iPhone升级记:从4.3.3到5.0.1:越狱篇
    iPhone升级记:从4.3.3到5.0.1:弯路篇
  • 原文地址:https://www.cnblogs.com/yangfanfan/p/11574210.html
Copyright © 2020-2023  润新知