微信小程序上傳圖片(附后端代碼)

幾乎每個程序都需要用到圖片。
在小程序中我們可以通過image組件顯示圖片。

當(dāng)然小程序也是可以上傳圖片的,微信小程序文檔也寫的很清楚。

上傳圖片

首先選擇圖片

通過wx.chooseImage(OBJECT)實現(xiàn)

官方示例代碼

wx.chooseImage({
  count: 1, // 默認(rèn)9
  sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
  sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認(rèn)二者都有
  success: function (res) {
    // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片
    var tempFilePaths = res.tempFilePaths
  }
})

圖片最多可以選擇9張, 也可以通過拍攝照片實現(xiàn),當(dāng)選擇完圖片之后會獲取到圖片路徑, 這個路徑在本次啟動期間有效。
如果需要保存就需要用wx.saveFile(OBJECT)

上傳圖片

通過wx.uploadFile(OBJECT) 可以將本地資源文件上傳到服務(wù)器。

原理就是客戶端發(fā)起一個 HTTPS POST 請求,其中 content-type為 multipart/form-data。

官方示例代碼

wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'http://example.weixin.qq.com/upload', //僅為示例,非真實的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

示例代碼

看完了文檔, 寫一個上傳圖片就沒有那么麻煩了,下面是真實場景的代碼

import constant from '../../common/constant';
Page({
  data: {
    src: "../../image/photo.png",  //綁定image組件的src
     //略...
  },
  onLoad: function (options) {
      //略... 
  },
  uploadPhoto() {
    var that = this; 
    wx.chooseImage({
      count: 1, // 默認(rèn)9
      sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認(rèn)二者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths;
        upload(that, tempFilePaths);
      }
    })
  }
})

function upload(page, path) {
  wx.showToast({
    icon: "loading",
    title: "正在上傳"
  }),
    wx.uploadFile({
      url: constant.SERVER_URL + "/FileUploadServlet",
      filePath: path[0], 
      name: 'file',
      header: { "Content-Type": "multipart/form-data" },
      formData: {
        //和服務(wù)器約定的token, 一般也可以放在header中
        'session_token': wx.getStorageSync('session_token')
      },
      success: function (res) {
        console.log(res);
        if (res.statusCode != 200) { 
          wx.showModal({
            title: '提示',
            content: '上傳失敗',
            showCancel: false
          })
          return;
        }
        var data = res.data
        page.setData({  //上傳成功修改顯示頭像
          src: path[0]
        })
      },
      fail: function (e) {
        console.log(e);
        wx.showModal({
          title: '提示',
          content: '上傳失敗',
          showCancel: false
        })
      },
      complete: function () {
        wx.hideToast();  //隱藏Toast
      }
    })
}

后端代碼

后端是用java寫的,一開始的時候,后端開始用了一些框架接收上傳的圖片,出現(xiàn)了各種問題,后來使用了純粹的Servlet就沒有了問題, 把代碼貼出來省的以后麻煩了。
注意: 代碼使用了公司內(nèi)部的框架,建議修改后再使用

public class FileUploadServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);
    
    public FileUploadServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JsonMessage<Object> message = new JsonMessage<Object>();
        EOSResponse eosResponse = null;
        String sessionToken = null;
        FileItem file = null;
        InputStream in = null;
        ByteArrayOutputStream swapStream1 = null;
        try {
            request.setCharacterEncoding("UTF-8"); 
            
            //1、創(chuàng)建一個DiskFileItemFactory工廠  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            //2、創(chuàng)建一個文件上傳解析器  
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            //解決上傳文件名的中文亂碼  
            upload.setHeaderEncoding("UTF-8");   
            // 1. 得到 FileItem 的集合 items  
            List<FileItem> items = upload.parseRequest(request);
            logger.info("items:{}", items.size());
            // 2. 遍歷 items:  
            for (FileItem item : items) {  
                String name = item.getFieldName();  
                logger.info("fieldName:{}", name);
                // 若是一個一般的表單域, 打印信息  
                if (item.isFormField()) {  
                    String value = item.getString("utf-8");  
                    if("session_token".equals(name)){
                        sessionToken = value;
                    }
                }else {
                    if("file".equals(name)){
                        file = item;
                    }
                }  
            }
            //session校驗
            if(StringUtils.isEmpty(sessionToken)){
                message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT);
                message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG);
            }
            String userId = RedisUtils.hget(sessionToken,"userId");
            logger.info("userId:{}", userId);
            if(StringUtils.isEmpty(userId)){
                message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT);
                message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG);
            }
            //上傳文件
            if(file == null){
            }else{
                swapStream1 = new ByteArrayOutputStream();
                
                in = file.getInputStream();
                byte[] buff = new byte[1024];
                int rc = 0;
                while ((rc = in.read(buff)) > 0) {
                    swapStream1.write(buff, 0, rc);
                }
                
                Usr usr = new Usr();
                usr.setObjectId(Integer.parseInt(userId));
                
                final byte[] bytes = swapStream1.toByteArray();
                
                eosResponse= ServerProxy.getSharedInstance().saveHeadPortrait(usr, new RequestOperation() {
                    
                    @Override
                    public void addValueToRequest(EOSRequest request) {
                        request.addMedia("head_icon_media", new EOSMediaData(EOSMediaData.MEDIA_TYPE_IMAGE_JPEG, bytes));
                    }
                });
                
                // 請求成功的場合
                if (eosResponse.getCode() == 0) {
                    message.setStatus(ConstantUnit.SUCCESS);
                } else {
                    message.setStatus(String.valueOf(eosResponse.getCode()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(swapStream1 != null){
                    swapStream1.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        PrintWriter out = response.getWriter();  
        out.write(JSONObject.toJSONString(message));  
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}```
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,825評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,511評論 19 139
  • 給提問的開發(fā)者的建議:提問之前先查詢 文檔、通過社區(qū)右上角搜索搜索已經(jīng)存在的問題。 寫一個簡明扼要的標(biāo)題,并且...
    極樂叔閱讀 14,616評論 0 3
  • 羊山中學(xué)九年級作文競賽實施方案 一、活動目的: 作文是反映學(xué)生內(nèi)心世界、知識世界的一扇窗戶。為了豐富學(xué)生的校園生活...
    鶴望蘭_889a閱讀 1,664評論 0 5
  • 目前,我國人才選拔機制和當(dāng)前考試制度,優(yōu)秀教育資源分配不均,傳統(tǒng)課堂教學(xué)又不能做到面面俱到,加上應(yīng)試教育的積重難返...
    大胡子瑞瑞閱讀 379評論 0 0

友情鏈接更多精彩內(nèi)容