小程序開發筆記(三):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,通過查看文件可確定圖片是否上傳成功。

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