Android中实现OkHttp上传文件到服务器并带进度
程序员文章站
2023-08-25 13:53:11
在上一讲中 okhttp下载文件并带进度条 中,我们知道怎样去下载文件了。那上传文件呢
一、编写服务器端
在上一讲服务器下新建uploadfileservlet,代码如...
在上一讲中 okhttp下载文件并带进度条 中,我们知道怎样去下载文件了。那上传文件呢
一、编写服务器端
在上一讲服务器下新建uploadfileservlet,代码如下:然后重启服务器!
@webservlet("/uploadfileservlet") @multipartconfig public class uploadfileservlet extends httpservlet { private static final long serialversionuid = 1l; public uploadfileservlet() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse * response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this.dopost(request, response); } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse * response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { system.out.println("dopost=="); request.setcharacterencoding("utf-8"); //获取file命名的part,注意要与android端一样 part part = request.getpart("file"); // 获取请求头,请求头的格式:form-data; name="file"; filename="snmp4j--api.zip" string header = part.getheader("content-disposition"); system.out.println(header); string filename = getfilename(header); // 存储路径 string savepath = "d:/huang/upload"; // 把文件写到指定路径 part.write(savepath + file.separator + filename); response.setcharacterencoding("utf-8"); printwriter writer = response.getwriter(); writer.print("上传成功"); } public string getfilename(string header) { /** * header 为 form-data; name="file"; filename="dial.png" * string[] temparr1 = * header.split(";");代码执行完之后,在不同的浏览器下,temparr1数组里面的内容稍有区别 * 火狐或者google浏览器下:temparr1={form-data,name="file",filename= * "snmp4j--api.zip"} * ie浏览器下:temparr1={form-data,name="file",filename="e:\snmp4j--api.zip"} */ string[] temparr1 = header.split(";"); /** * 火狐或者google浏览器下:temparr2={filename,"snmp4j--api.zip"} * ie浏览器下:temparr2={filename,"e:\snmp4j--api.zip"} */ string[] temparr2 = temparr1[2].split("="); // 获取文件名,兼容各种浏览器的写法 string filename = temparr2[1].substring(temparr2[1].lastindexof("\\") + 1).replaceall("\"", ""); return filename; } }
二、android端
1.布局,上一讲activity_main代码中添加 :
<button android:id="@+id/ok_post_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="上传文件" /> <textview android:id="@+id/post_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="0" /> <progressbar android:id="@+id/post_progress" style="?android:attr/progressbarstylehorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100" />
2.okhttputil新增上传文件方法:
public static void postfile(string url, final progresslistener listener, callback callback, file...files){ multipartbody.builder builder = new multipartbody.builder(); builder.settype(multipartbody.form); log.i("huang","files[0].getname()=="+files[0].getname()); //第一个参数要与servlet中的一致 builder.addformdatapart("file",files[0].getname(), requestbody.create(mediatype.parse("application/octet-stream"),files[0])); multipartbody multipartbody = builder.build(); request request = new request.builder().url(url).post(new progressrequestbody(multipartbody,listener)).build(); okhttpclient.newcall(request).enqueue(callback); }
3.progressrequestbody是自定义requestbody类,用来监听进度:
public class progressrequestbody extends requestbody { public static final int update = 0x01; private requestbody requestbody; private progresslistener mlistener; private bufferedsink bufferedsink; private myhandler myhandler; public progressrequestbody(requestbody body, progresslistener listener) { requestbody = body; mlistener = listener; if (myhandler==null){ myhandler = new myhandler(); } } class myhandler extends handler { //放在主线程中显示 public myhandler() { super(looper.getmainlooper()); } @override public void handlemessage(message msg) { switch (msg.what){ case update: progressmodel progressmodel = (progressmodel) msg.obj; if (mlistener!=null)mlistener.onprogress(progressmodel.getcurrentbytes(),progressmodel.getcontentlength(),progressmodel.isdone()); break; } } } @override public mediatype contenttype() { return requestbody.contenttype(); } @override public long contentlength() throws ioexception { return requestbody.contentlength(); } @override public void writeto(bufferedsink sink) throws ioexception { if (bufferedsink==null){ bufferedsink = okio.buffer(sink(sink)); } //写入 requestbody.writeto(bufferedsink); //刷新 bufferedsink.flush(); } private sink sink(bufferedsink sink) { return new forwardingsink(sink) { long byteswritten = 0l; long contentlength = 0l; @override public void write(buffer source, long bytecount) throws ioexception { super.write(source, bytecount); if (contentlength==0){ contentlength = contentlength(); } byteswritten += bytecount; //回调 message msg = message.obtain(); msg.what = update; msg.obj = new progressmodel(byteswritten,contentlength,byteswritten==contentlength); myhandler.sendmessage(msg); } }; } }
4.在mainactivity添加上传按钮点击事件,代码如下:
file file = new file(basepath + "/1.mp4"); string posturl = "http://192.168.0.104:8080/okhttpserver/uploadfileservlet"; okhttputil.postfile(posturl, new progresslistener() { @override public void onprogress(long currentbytes, long contentlength, boolean done) { log.i(tag, "currentbytes==" + currentbytes + "==contentlength==" + contentlength + "==done==" + done); int progress = (int) (currentbytes * 100 / contentlength); post_progress.setprogress(progress); post_text.settext(progress + "%"); } }, new callback() { @override public void onfailure(call call, ioexception e) { } @override public void onresponse(call call, response response) throws ioexception { if (response != null) { string result = response.body().string(); log.i(tag, "result===" + result); } } }, file);
相关效果图:
上传完成后,在电脑d:\huang\upload下可以看到:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: Github帮助功能的使用