图片上传功能(ssm,ajax,form)(三种方式)

@跃焱邵隼

这里提供三种方式:(具体可参考https://www.yueyanshaosun.cn/html/VYyssNotes/javaEnder.html);

方式一:

<!--
说明:这种方式 是表单提交 需要跳转(可以通过内嵌套iframe优化)
前端:
<div class="example">
      <img src="<%=request.getContextPath()%>/upload/123.png">
     <form action="cors/addProduct" method="post" enctype="multipart/form-data">
     <label>用户id:</label><input type="password" name="userId"><br>
     <label>文件:</label><input type="file" name="pictureFile"><br>
     <input type="submit">
     </form>
</div>
后端
1:依赖:

 <dependency>
     <groupId>commons-fileupload</groupId>
         <artifactId>commons-fileupload</artifactId>
         <version>1.3</version>
  </dependency>
  <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>1.4</version>
 </dependency>

 2:spring-servlet.xml:
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="defaultEncoding" value="utf-8"/>
     <property name="maxInMemorySize" value="10240"/>
     <property name="maxUploadSize" value="-1"/>
  </bean>

  3:controller:
  @RequestMapping(value="/index")
       public String index(){

           return "index";
       }

    @RequestMapping(value="/cors/addProduct",method=RequestMethod.POST)
    @ResponseBody
    public ModelAndView addProduct(int userId,MultipartFile pictureFile) throws IllegalStateException, IOException {

        productService.doAddProduct(userId,pictureFile);

        return new ModelAndView("redirect:/index");
    }

    4:service:
    public String doAddProduct(int userId,MultipartFile pictureFile) throws IllegalStateException, IOException {
                 Product product=new Product();
                //使用UUID给图片重命名,并去掉“-”
                //String name = UUID.randomUUID().toString().replaceAll("-", "");
                 String name="123";
                //获取文件的扩展名
                String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
                //设置图片上传路径
                String url = request.getSession().getServletContext().getRealPath("/upload");
                System.out.println(url);
                //以绝对路径保存重名命后的图片
                pictureFile.transferTo(new File(url+"/"+name + "." + ext));
                //把图片存储路径保存到数据库
                product.setName(name);
                product.setPath("upload/"+name + "." + ext);
                product.setUserId(userId);
                int result=addProduct(product);
                return null;
    }


 -->

 

方式二:

<!--
   说明 :这种方式不需要跳转页面;
   需要:上面的配置文件;以及前端layui引入
   方便起见 这里我们只写controller了。

   html:
   <div class="example">
     <div class="layui-upload">
      <button type="button" class="layui-btn" id="test2">多图片上传</button>
      <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
      预览图:
       <div class="layui-upload-list" id="demo2"></div>
      </blockquote>
      </div>
   </div>

  js:
 layui.use('upload', function(){
  var $ = layui.jquery
  ,upload = layui.upload;

  //多图片上传
  upload.render({
    elem: '#test2'
    ,url: 'cors/addProduct2'
    ,data:{ //同时携带的数据;
        userId:function(){
            //$('#id').attr("userId");
            return '123';
        }
    }
    ,multiple: true
    ,before: function(obj){
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
        $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
      });
    }
    ,done: function(res){
      console.log(res)
    }
  });

  //controller
   @RequestMapping(value="/cors/addProduct2")
      @ResponseBody
    public Map<String,Object> manyImageUpload(MultipartFile file,int userId) throws IOException{
        System.out.println("---------upload------------");
        System.out.print("userId"+userId);
        //调用服务层来处理数据
        System.out.println("=="+file.getName());//文件名字
        System.out.println("1="+file.getContentType());
        System.out.println("2="+file.getOriginalFilename());
        System.out.println("3="+file.getSize());
        System.out.println("--"+file.getInputStream());
        String url = request.getSession().getServletContext().getRealPath("/upload");
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        file.transferTo(new File(url+"/"+userId + "head." + ext));
        //file.transferTo(new File(url+"/"+userId + file.getOriginalFilename());

        //返回结果
        Map<String,Object> aMap=new HashMap<String, Object>();
        aMap.put("code", 0);
        return aMap;
    }

ps如果是多图列表上传(其原理还是单图循环上传,所以后端改动不大,除了图片命名的地方改一下,防止覆盖)

html:(layui多图片上传;实际也是单文件循环上传 )
<div class="example">
 <div class="layui-upload">
  <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
  <div class="layui-upload-list">
    <table class="layui-table">
      <thead>
        <tr><th>文件名</th>
        <th>大小</th>
        <th>状态</th>
        <th>操作</th>
      </tr></thead>
      <tbody id="demoList"></tbody>
    </table>
  </div>
  <button type="button" class="layui-btn" id="testListAction">开始上传</button>
</div>
</div>
js:
  //多文件列表示例
  var demoListView = $('#demoList')
  ,uploadListIns = upload.render({
    elem: '#testList'
    ,url: 'cors/addProduct2'
    ,data:{
            userId:function(){
                //$('#id').attr("userId");
                return '123';
            }
    }
    ,accept: 'file'
    ,multiple: true
    ,auto: false
    ,bindAction: '#testListAction'
    ,choose: function(obj){
      var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
      //读取本地文件
      obj.preview(function(index, file, result){
        var tr = $(['<tr id="upload-'+ index +'">'
          ,'<td>'+ file.name +'</td>'
          ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
          ,'<td>等待上传</td>'
          ,'<td>'
            ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
            ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
          ,'</td>'
        ,'</tr>'].join(''));

        //单个重传
        tr.find('.demo-reload').on('click', function(){
          obj.upload(index, file);
        });

        //删除
        tr.find('.demo-delete').on('click', function(){
          delete files[index]; //删除对应的文件
          tr.remove();
          uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
        });

        demoListView.append(tr);
      });
    }
    ,done: function(res, index, upload){
      if(res.code == 0){ //上传成功
        var tr = demoListView.find('tr#upload-'+ index)
        ,tds = tr.children();
        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
        tds.eq(3).html(''); //清空操作
        return delete this.files[index]; //删除文件队列已经上传成功的文件
      }
      this.error(index, upload);
    }
    ,error: function(index, upload){
      var tr = demoListView.find('tr#upload-'+ index)
      ,tds = tr.children();
      tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
      tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
  });

 -->

 

方式三:

html:
<form class="form-horizontal" enctype="multipart/form-data" role="form" id="testform">

                    <div>
                     <img src="" width="100px" height="100px" class='img3'>

                        <label for="requirement" class="">图片上传</label>
                        <div class="input-group">
                                <input id="photoCover" class="form-control" readonly type="text">
                                <label class="input-group-btn">
                                    <input id="file3" type="file" name="file" style="display:none">
                                    <span class="btn btn-default">选择文件</span>
                                </label>
                            </div>
                    </div>

                    <div class="control-group">
                        <a class="" οnclick="saveUser2()">点击上传</a>
                    </div>
</form>

js:
//用于显示图片;
$(function () {
    $("#file3").change(function (e) {
        var file = e.target.files[0] || e.dataTransfer.files[0];
        $('#photoCover').val(document.getElementById("file3").files[0].name);
        if (file) {
            var reader = new FileReader();
            reader.onload = function () {
                $(".img3").attr("src", this.result);
            }

            reader.readAsDataURL(file);
        }
    });
})

Jquery实现
function saveUser2() {
           //var id = $("#id").val().trim();
          //var uname = $("#uname").val().trim();
          //var pwd = $("#pwd").val().trim();
          var file = document.getElementById("file3").files[0];
          var formData = new FormData();
          formData.append('userId', 123456);
          formData.append('file', file);

          if(file){
            $.ajax({
              url: "cors/addProduct2",
              type: "post",
              data: formData,
              contentType: false,
              processData: false,
              mimeType: "multipart/form-data",
              success: function (data) {
                  console.log(data);
              },
              error: function (data) {
                  console.log(data);
              }
          });
       }
}

后端controller和方法二是一样的(layui方法);如果多图上传;类似处理

如要源码可联系我;也可访问https://www.yueyanshaosun.cn获取

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

跃焱邵隼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值