2018-05-29 10:12:03 1684瀏覽
今天扣丁學(xué)堂小編給大家詳細(xì)介紹一下關(guān)于HTML5視頻教程微信小程序上傳圖片功能及后端代碼,幾乎每個(gè)程序都需要用到圖片,在小程序中我們可以通過image組件顯示圖片,當(dāng)然小程序也是可以上傳圖片的,微信小程序文檔也寫的很清楚。下面我們來一起看一下吧。
wx.chooseImage({ count:1,//默認(rèn)9 sizeType:['original','compressed'],//可以指定是原圖還是壓縮圖,默認(rèn)二者都有 sourceType:['album','camera'],//可以指定來源是相冊還是相機(jī),默認(rèn)二者都有 success:function(res){ //返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片 vartempFilePaths=res.tempFilePaths } })
wx.chooseImage({ success:function(res){ vartempFilePaths=res.tempFilePaths wx.uploadFile({ url:'http://m.dionly.net.cn/upload',//僅為示例,非真實(shí)的接口地址 filePath:tempFilePaths[0], name:'file', formData:{ 'user':'test' }, success:function(res){ vardata=res.data //dosomething } }) } })
importconstantfrom'../../common/constant'; Page({ data:{ src:"../../image/photo.png",//綁定image組件的src //略... }, onLoad:function(options){ //略... }, uploadPhoto(){ varthat=this; wx.chooseImage({ count:1,//默認(rèn)9 sizeType:['compressed'],//可以指定是原圖還是壓縮圖,默認(rèn)二者都有 sourceType:['album','camera'],//可以指定來源是相冊還是相機(jī),默認(rèn)二者都有 success:function(res){ //返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片 vartempFilePaths=res.tempFilePaths; upload(that,tempFilePaths); } }) } }) functionupload(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; } vardata=res.data page.setData({//上傳成功修改顯示頭像 src:path[0] }) }, fail:function(e){ console.log(e); wx.showModal({ title:'提示', content:'上傳失敗', showCancel:false }) }, complete:function(){ wx.hideToast();//隱藏Toast } }) }
publicclassFileUploadServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; privatestaticLoggerlogger=LoggerFactory.getLogger(FileUploadServlet.class); publicFileUploadServlet(){ super(); } protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ JsonMessage<Object>message=newJsonMessage<Object>(); EOSResponseeosResponse=null; StringsessionToken=null; FileItemfile=null; InputStreamin=null; ByteArrayOutputStreamswapStream1=null; try{ request.setCharacterEncoding("UTF-8"); //1、創(chuàng)建一個(gè)DiskFileItemFactory工廠 DiskFileItemFactoryfactory=newDiskFileItemFactory(); //2、創(chuàng)建一個(gè)文件上傳解析器 ServletFileUploadupload=newServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //1.得到FileItem的集合items List<FileItem>items=upload.parseRequest(request); logger.info("items:{}",items.size()); //2.遍歷items: for(FileItemitem:items){ Stringname=item.getFieldName(); logger.info("fieldName:{}",name); //若是一個(gè)一般的表單域,打印信息 if(item.isFormField()){ Stringvalue=item.getString("utf-8"); if("session_token".equals(name)){ sessionToken=value; } }else{ if("file".equals(name)){ file=item; } } } //session校驗(yàn) if(StringUtils.isEmpty(sessionToken)){ message.setStatus(StatusCodeConstant.SESSION_TOKEN_TIME_OUT); message.setErrorMsg(StatusCodeConstant.SESSION_TOKEN_TIME_OUT_MSG); } StringuserId=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=newByteArrayOutputStream(); in=file.getInputStream(); byte[]buff=newbyte[1024]; intrc=0; while((rc=in.read(buff))>0){ swapStream1.write(buff,0,rc); } Usrusr=newUsr(); usr.setObjectId(Integer.parseInt(userId)); finalbyte[]bytes=swapStream1.toByteArray(); eosResponse=ServerProxy.getSharedInstance().saveHeadPortrait(usr,newRequestOperation(){ @Override publicvoidaddValueToRequest(EOSRequestrequest){ request.addMedia("head_icon_media",newEOSMediaData(EOSMediaData.MEDIA_TYPE_IMAGE_JPEG,bytes)); } }); //請求成功的場合 if(eosResponse.getCode()==0){ message.setStatus(ConstantUnit.SUCCESS); }else{ message.setStatus(String.valueOf(eosResponse.getCode())); } } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(swapStream1!=null){ swapStream1.close(); } }catch(IOExceptione){ e.printStackTrace(); } try{ if(in!=null){ in.close(); } }catch(IOExceptione){ e.printStackTrace(); } } PrintWriterout=response.getWriter(); out.write(JSONObject.toJSONString(message)); } protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ doGet(request,response); } }
以上就是關(guān)于扣丁學(xué)堂HTML5視頻教程之微信小程序圖片上傳及源碼的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,想要了解更多內(nèi)容的小伙伴可以登錄扣丁學(xué)堂官網(wǎng)查詢。扣丁學(xué)堂是專業(yè)的HTML5培訓(xùn)機(jī)構(gòu),不僅有專業(yè)的老師和與時(shí)俱進(jìn)的課程體系,還有大量的HTML5在線教程供學(xué)員掛看學(xué)習(xí)哦??鄱W(xué)堂H5技術(shù)交流群:559883758。
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“HTML5開發(fā)技術(shù)資訊”的相關(guān)文章>>