| | |
| | | package com.dayu.pipirrapp.net.upload; |
| | | |
| | | import java.io.File; |
| | | import java.io.FileInputStream; |
| | | import java.io.IOException; |
| | | |
| | | import okhttp3.MediaType; |
| | | import okhttp3.RequestBody; |
| | | import okio.Buffer; |
| | | import okio.BufferedSink; |
| | | import okio.BufferedSource; |
| | | import okio.ForwardingSink; |
| | | import okio.Okio; |
| | | import okio.Sink; |
| | | |
| | | /** |
| | | * ProgressRequestBody - |
| | |
| | | * @since 2024-11-28 |
| | | */ |
| | | public class ProgressRequestBody extends RequestBody { |
| | | private File file; |
| | | private ProgressListener listener; |
| | | private MediaType mediaType; |
| | | private final RequestBody requestBody; |
| | | private final ProgressListener progressListener; |
| | | |
| | | public ProgressRequestBody(File file, ProgressListener listener, String mimeType) { |
| | | this.file = file; |
| | | this.listener = listener; |
| | | this.mediaType = MediaType.parse(mimeType); |
| | | public ProgressRequestBody(RequestBody requestBody, ProgressListener progressListener) { |
| | | this.requestBody = requestBody; |
| | | this.progressListener = progressListener; |
| | | } |
| | | |
| | | @Override |
| | | public MediaType contentType() { |
| | | return mediaType; |
| | | return requestBody.contentType(); |
| | | } |
| | | |
| | | @Override |
| | | public long contentLength() throws IOException { |
| | | return requestBody.contentLength(); |
| | | } |
| | | |
| | | @Override |
| | | public void writeTo(BufferedSink sink) throws IOException { |
| | | try (FileInputStream fileInputStream = new FileInputStream(file); |
| | | BufferedSource source = (BufferedSource) Okio.source(fileInputStream)) { |
| | | long totalBytes = file.length(); |
| | | long bytesWritten = 0; |
| | | long read; |
| | | byte[] buffer = new byte[2048]; |
| | | while ((read = source.read(buffer)) != -1) { |
| | | sink.write(buffer, 0, (int) read); |
| | | bytesWritten += read; |
| | | if (listener != null) { |
| | | listener.onProgress(bytesWritten, totalBytes); |
| | | Sink progressSink = new ForwardingSink(sink) { |
| | | long totalBytesWritten = 0; |
| | | |
| | | @Override |
| | | public void write(Buffer source, long byteCount) throws IOException { |
| | | super.write(source, byteCount); |
| | | totalBytesWritten += byteCount; |
| | | if (progressListener != null) { |
| | | progressListener.onProgress(totalBytesWritten, contentLength(),false); |
| | | } |
| | | } |
| | | }; |
| | | BufferedSink bufferedSink = Okio.buffer(progressSink); |
| | | requestBody.writeTo(bufferedSink); |
| | | bufferedSink.flush(); |
| | | } |
| | | } |
| | | |
| | | |
| | | } |