小程序开发笔记(三):SSM框架实现微信小程序的图片上传

微信富文本编辑器editor的插入图片功能,可查看开发文档的EditorContext.insertImage(Object object)方法。

插入的图片地址为临时文件地址,需要将图片上传然后将图片地址替换为实际存储地址。
对于图片上传有两种方案:

1. 在编辑器插入图片成功时,就将图片上传,并返回实际地址进行替换。
优点: 服务器可以在用户编辑期间实现图片上传,用户无需等待图片上传成功,可以进行其他编写操作。
缺点: 用户在编写过程需要替换已插入的图片,这是后台会存在之前的图片,此图片为废弃图片,需要进行删除操作,否则会占用后台资源。因此也增加了对后台的请求。

2. 在用户编写完文章后,获取文章内相关图片的临时地址,再上传至后台,获取实际地址进行替换。
优点: 可以准确定位文章内容图片,不会产生废弃图片,不用实现删除操作。减少和后台交互操作。
缺点: 用户在编辑完成后,需要等待图片上传时间。且微信的wx.uploadFile方法是单图片上传形式,需要集中发送多个请求。若图片较多,网络不佳,会造成用户等待时间过长,影响用户体验。

一、editor.js

data:{
    tempimageid: 1,
    imageid: 1,
    image:[
      {
        imageid:0,
        imageurl:'null'
      }
    ]
}	
//插入图片
  insertImage() {
    const that = this
    //选择图片
    wx.chooseImage({
      count: 1,
      success: function (res) {
      //调用EditorContext.insertImage(Object object)方法
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],  //插入图片临时文件地址
          data: {
             id: that.data.tempimageid, //临时图片id
            // role: ''
          },
          height: '80%',
          width: '80%',
          alt: 'img',
          success: function () {
            that.setData({
              tempimageid:that.data.tempimageid+1//临时图片id加1
            })
          }
        }),
        //上传图片
        wx.uploadFile({
          url: 'http://localhost:8080/zhigj/image/upload.action',//图片上传处理接口
          filePath: res.tempFilePaths[0],
          name:'file',
          formData:{
            id: that.data.imageid	//设置图片id,需与临时图片id一致,所以初始化赋值时两个均为0即可
          },
          success: function(res){  
            that.setData({
              imageid: that.data.imageid+1//图片id加1
            }) 
            that.data.image.push(JSON.parse(res.data))    //将返回的图片地址存储进数组内。
          },
          fail: function(error){
            console.log(error)
          }
        })        
      }
    })
  },
  //替换图片
replaceImage() {
    const that = this
    //获取编辑器内容
     that.editorCtx.getContents({
            success: function (res) {          //获取返回的delta对象                       
              var length = res.delta.ops.length;
              for (var i = 0; i < length; i++) {
                if(res.delta.ops[i].attributes){     //筛选出里面的图片
                  var id = parseInt(res.delta.ops[i].attributes['data-custom'].trim().slice(3));//取出临时图片的id
                  for (var j = 1; j < that.data.image.length; j++){               
                    if (id === that.data.image[j].imageid){			//与实际图片地址的id比较,并替换图片地址
                      res.delta.ops[i].insert.image = that.data.image[j].imageurl
                      break;                           
                    }        
                  }
                }}
      })
  },

二、java后台实现图片上传
导入jar包
commons-fileupload.jar包和 commons-io.jar包下载地址:
http://commons.apache.org/proper/commons-fileupload/
http://commons.apache.org/proper/commons-io/

配置springmvc-config.xml

<!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxUploadSize" value="32505856"/>
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="4096"/>
    </bean>

Controller类

package com.itheima.core.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 /**
 * 文章图片上传Controller类
 */
@Controller
@RequestMapping("/image")
public class ImageController { 
    private Logger logger = Logger.getLogger(ImageController.class);
    /**
     * @param request
     * @return 成功返回success,失败返回error
     */
    @ResponseBody
    @RequestMapping("/upload.action")
    public String upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, Integer id) throws IOException {
        request.setCharacterEncoding("UTF-8");
        logger.info("执行图片上传");
        String url = null;
        if(!file.isEmpty()) {
            logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            logger.info("图片初始名称为:" + fileName + " 类型为:" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    logger.info("项目在容器中实际发布运行的根路径"+realPath);                 
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = realPath + "/uploads/" + trueFileName;
                    logger.info("文件的绝对路径:" + path);
                    url = "http://localhost:8080/zhigj/uploads/"+trueFileName;
                    logger.info("文件访问相对地址:" + url);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传成功");
                }else {
                    return "error";
                }
            }else {
                return "error";
            }
        }else {
            return "error";
        }
        //Map存储图片相对地址和id
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("imageurl", url);
        map.put("imageid", id);
        ObjectMapper mapper = new ObjectMapper();
        //转化为Json字符串格式并返回
		String JsonImage = mapper.writeValueAsString(map);
        return JsonImage;
    }
}

E:\java.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\zhigj\uploads,通过查看文件可确定图片是否上传成功。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章