微信小程序填坑之路(三)--上傳頭像

上傳頭像, 使用wx.chooseImage({})後 在使用wx.uploadFile({})結合起來使用.

示例代碼:

 


Page({
  data: {
    src: "../../image/photo.png",  //綁定image組件的src
     //略...
  },
  onLoad: function (options) {
      //略... 
  },
  uploadPhoto() {
    var that = this; 
    wx.chooseImage({
      count: 1, // 默認9
      sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作爲img標籤的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: {
        //和服務器約定的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
      }
    })
}


 

 

後端代碼

 

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、創建一個DiskFileItemFactory工廠  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            //2、創建一個文件上傳解析器  
            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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章