关注分享主机优惠活动
国内外VPS云服务器

在微信小程序中上传带有后端代码的图片(在微信小程序中上传图片)

这次给大家带来的是微信小程序中上传图片后端代码。微信小程序上传图片有哪些注意事项?以下是实际案例。让我们来看看。

当然小程序也可以上传图片,微信小程序文档也写的很清楚。

上传图片

首先选择图片

由wx.chooseImage(OBJECT)实现

在微信小程序中上传带有后端代码的图片(在微信小程序中上传图片)-主机频道

官方样本代码

Wx.chooseImage({ count: 1,// default 9 sizeType:

官方样本代码

wx . choose image({ success:function(RES){ var tempfile paths = RES . tempfile paths wx . uploadfile({ URL:& # 039;http://example.weixin.qq.com/upload',//仅举例,虚幻接口地址filepath: tempfilepaths [0],name:& # 039;文件& # 039;,表单数据:{ & # 039;用户& # 039;: '测试& # 039;},success:function(RES){ var data = res.data//dosomething}}})示例代码

看完公文,写一张上传的图片就没那么麻烦了。下面是真实场景的代码。

从& # 039;导入常量;../../common/常数& # 039;;page({ data:{ src:& quot;../../image/photo . png & quot;,//src //省略...}的绑定图像组件,onload:function(options){//省略...},upload photo(){ var that = this;Wx.chooseImage({ count: 1,//default 9 size type:[& # 039;压缩& # 039;],//可以指定是原图还是压缩图。默认情况下,它们都有source type:[& # 039;相册& # 039;, '相机& # 039;],//可以指定来源是相册还是相机。默认两个都成功:function (res) {//返回选中照片的本地文件路径列表。tempFilePath可以作为img标签的src属性来显示图片var tempfile paths = RES . tempfile paths;上传(即tempfile paths);} }) }})函数上传(页面,路径){ wx . show toast({ icon:& quot;正在加载& quot,标题:& quot上传”。})、wx.uploadFile({ url: constant。SERVER _ URL+& quot;/file upload servlet & quot;,文件路径:路径[0],名称:& # 039;文件& # 039;,标题:{ & quotcontent -Type & quot;:& quotmultipart/form -data & quot;}、formData: {//以及服务器同意的令牌,一般也可以放在头& # 039;会话令牌& # 039;:wx . getstoragesync(& # 039;会话令牌& # 039;)},success:function(RES){ console . log(RES);if (res.statusCode!= 200){ wx . show modal({ title:& # 039;提示& # 039;,内容:& # 039;上传失败& # 039;,showCancel: false })返回;} var data = RES . data page . setdata({//上传成功修改显示头像src: path [0]}},fail:function(e){ console . log(e);wx . show modal({ title:& # 039;提示& # 039;,内容:& # 039;上传失败& # 039;,showCancel: false }) },complete:function(){ wx . hide toast();//隐藏toast}}}后端代码

后端用java写的。一开始后端开始用一些框架接收上传的图片,出现了各种问题。后来用纯Servlet就没问题了,省去了贴代码后的麻烦。

注意:代码使用的是公司内部框架,建议修改后再使用。

公共类FileUploadServlet扩展http servlet { private static final long serial version uid = 1L;private static Logger Logger = Logger factory . get Logger(fileuploadservlet . class);public FileUploadServlet(){ super();} protected void doGet(http servlet request请求,HttpServletResponse响应)抛出ServletException,IOException { JsonMessage & ltObject & gtmessage = new JsonMessage & ltObject & gt();EOSResponse eosResponse = nullString sessionToken = nullFileItem file = nullInputStream in = nullByteArrayOutputStream swap stream 1 = null;请尝试{ request . setcharacterencoding(& quot;ut F-8 & quot;);//1,创建一个diskfileitemcfactory工厂diskfileitemcfactory = newdiskfileitemcfactory();//2.创建一个文件上传解析器servlet file upload upload = new servlet file upload(工厂);//解决中文乱码upload . setheaderencoding(& quot;ut F-8 & quot;);// 1.获取FileItem 的集合项列表items = upload.parseRequest(请求);logger.info(&quot项目:{ } & quot,items . size());// 2.遍历项目:for(file item item:items){ string name = item . get field name();logger.info(&quot字段名:{ } & quot,姓名);//如果是一般的表单域,打印信息If(item . is formfield()){ string value = item . getstring(" ut F-8 & quot;);如果(& quot会话令牌& quot。equals(name)){ session token = value;} } else { if(& quot;文件& quot。equals(name)){ file = item;} } }//会话检查if(String utils . isempty(session token)){ message . set status(status code constant . session _ token _ time _ out);message . set error msg(StatusCodeConstant。会话_令牌_超时_消息);} String userId = redis utils . hget(session token,& quotuserId & quot);logger.info(&quotuserId:{ } & quot;,userId);if(string utils . isempty(userId)){ message . set status(StatusCodeConstant。会话_令牌_超时);message . set error msg(StatusCodeConstant。会话_令牌_超时_消息);}//上传文件if(file = = null){ } else { swap stream 1 = newbytearray output stream();in = file . getinputstream();byte[] buff =新字节[1024];int RC = 0;while((RC = in . read(buff))& gt;0) { swapStream1.write(buff,0,RC);} Usr Usr = new Usr();usr . set objectid(integer . parse int(userId));final byte[]bytes = swap stream 1 . tobytearray();EOS response = server proxy . getsharedinstance()。saveHeadPortrait(usr,new request operation(){ @ Override public void addValueToRequest(EOS request){ request . add media(& quot;head _ icon _ media & quot,新EOSMediaData(EOSMediaData。MEDIA_TYPE_IMAGE_JPEG,字节));} });//请求成功的场合if(EOS response . getcode()= = 0){ message . set status(constant unit . success);} else { message . set status(string . value of(EOS response . getcode()));} } } catch(异常e){ e . printstacktrace();}最后{ try { if(swapStream1!= null){ swap stream 1 . close();} } catch(io exception e){ e . printstacktrace();}试试{ if(in!= null){ in . close();} } catch(io exception e){ e . printstacktrace();} } PrintWriter out = response . getwriter();out . write(JSON object . tojsonstring(message));} protected void doPost(http servlet request请求,HttpServletResponse响应)抛出ServletException,IOException { doGet(请求,响应);}}相信你看完这个案例已经掌握了方法。更多精彩请关注即时码站其他相关文章!

推荐阅读:

js三种使用方式的案例讲解(附代码)

如何使用微信小程序上传图片

未经允许不得转载:主机频道 » 在微信小程序中上传带有后端代码的图片(在微信小程序中上传图片)

评论 抢沙发

评论前必须登录!