欧美成人午夜免费全部完,亚洲午夜福利精品久久,а√最新版在线天堂,另类亚洲综合区图片小说区,亚洲欧美日韩精品色xxx

扣丁學(xué)堂HTML5視頻教程之微信小程序圖片上傳(附后端代碼)

2018-05-29 10:12:03 1684瀏覽

今天扣丁學(xué)堂小編給大家詳細(xì)介紹一下關(guān)于HTML5視頻教程微信小程序上傳圖片功能及后端代碼,幾乎每個(gè)程序都需要用到圖片,在小程序中我們可以通過image組件顯示圖片,當(dāng)然小程序也是可以上傳圖片的,微信小程序文檔也寫的很清楚。下面我們來一起看一下吧。



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

官方示例代碼

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
}
})

圖片最多可以選擇9張,也可以通過拍攝照片實(shí)現(xiàn),當(dāng)選擇完圖片之后會(huì)獲取到圖片路徑,這個(gè)路徑在本次啟動(dòng)期間有效。

如果需要保存就需要用wx.saveFile(OBJECT)

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

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

官方示例代碼

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
}
})
}
})

示例代碼

看完了官方文檔,寫一個(gè)上傳圖片就沒有那么麻煩了,下面是真實(shí)場景的代碼

  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);
  }
  }

后端是用java寫的,一開始的時(shí)候,后端開始用了一些框架接收上傳的圖片,出現(xiàn)了各種問題,后來使用了純粹的Servlet就沒有了問題,把代碼貼出來省的以后麻煩了。

注意:代碼使用了公司內(nèi)部的框架,建議修改后再使用

以上就是關(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)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】



查看更多關(guān)于“HTML5開發(fā)技術(shù)資訊”的相關(guān)文章>>

標(biāo)簽: HTML5培訓(xùn) HTML5視頻教程 AngularJS HTML5在線視頻 HTML5從入門到精通 微信小程序

熱門專區(qū)

暫無熱門資訊

課程推薦

微信
微博
15311698296

全國免費(fèi)咨詢熱線

郵箱:codingke@1000phone.com

官方群:148715490

北京千鋒互聯(lián)科技有限公司版權(quán)所有   北京市海淀區(qū)寶盛北里西區(qū)28號(hào)中關(guān)村智誠科創(chuàng)大廈4層
京ICP備2021002079號(hào)-2   Copyright ? 2017 - 2022
返回頂部 返回頂部