Android中实现OkHttp上传文件到服务器并带进度

作者:Gary__123456 时间:2023-02-10 21:44:09 

在上一讲中 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);

相关效果图:

Android中实现OkHttp上传文件到服务器并带进度 

上传完成后,在电脑D:\huang\upload下可以看到:

Android中实现OkHttp上传文件到服务器并带进度

源码下载

来源:http://blog.csdn.net/gary__123456/article/details/74159042

标签:OkHttp,上传,文件
0
投稿

猜你喜欢

  • 一篇文章带你了解Java Stream流

    2022-11-05 10:26:18
  • 如何在Golang中运行JavaScript

    2022-11-03 14:50:48
  • Java多线程的用法详解

    2021-10-29 19:20:59
  • 解决springboot环境切换失效的问题

    2023-11-11 20:40:35
  • eclipse springboot工程打war包方法及再Tomcat中运行的方法

    2023-04-14 09:21:40
  • 常用的C语言排序算法(两种)

    2022-12-28 02:28:37
  • Android shell命令行中过滤adb logcat输出的方法

    2023-11-23 07:30:29
  • 在winform下实现左右布局多窗口界面的方法

    2023-02-23 11:31:51
  • Android权限如何禁止以及友好提示用户开通必要权限详解

    2023-10-09 04:29:41
  • JMeter中的后端监听器的实现

    2022-07-24 17:58:35
  • Android利用Canvas类绘制图形

    2022-09-17 14:22:02
  • SpringBoot实现模块日志入库的项目实践

    2022-06-15 10:32:49
  • Spring Boot 项目创建的详细步骤(图文)

    2023-03-23 20:11:55
  • 详解Java中Duration类的使用方法

    2021-07-30 20:09:28
  • Spring Boot配置Thymeleaf(gradle)的简单使用

    2023-04-18 07:41:42
  • Java类之间的关系图_动力节点Java学院整理

    2022-07-31 23:03:46
  • Android app应用多语言切换功能实现

    2023-12-27 22:06:27
  • Java如何把int类型转换成byte

    2023-03-13 11:12:39
  • HelloSpringMVC注解版实现步骤解析

    2021-07-21 01:58:42
  • Java中的MapStruct用法详解

    2022-10-05 12:18:13
  • asp之家 软件编程 m.aspxhome.com