хотите загрузить файл на сервер, используя асинхронную задачу (в фоновом режиме) и multipart с okhttp 3, а также получить прогресс загрузки - PullRequest
0 голосов
/ 25 апреля 2019

хотите загрузить файл с некоторым другим контентом на сервер, используя okhttp 3 в фоновом режиме, используя multipart а также получить информацию о ходе загрузки, а также уведомить о ходе работы адаптера для определенного элемента.

Ответы [ 2 ]

0 голосов
/ 25 апреля 2019

Попробуйте это

RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "name", videoBody)
                .build();
        requestBuilder = new Request.Builder()
                .url(mainUrlString)
                .post(requestBody)
                .build();
0 голосов
/ 25 апреля 2019

попробуйте это, чтобы загрузить файл

private PrintWriter writer;
private OutputStream outputStream;

public void addFilePart(File uploadFile) throws IOException {

    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

    String fileName = uploadFile.getName();
    writer.append("--").append(boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"").append(fileName).append("\"")
            .append(LINE_FEED);
    writer.append("Content-Type: " + "application/octet-stream")
            .append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead;
    float bytesWritten = 0;
    int totalSize = (int) uploadFile.length();
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        if (isCanceled)
            return;
        outputStream.write(buffer, 0, bytesRead);
        bytesWritten += bytesRead;
        int progress = (int) ((bytesWritten * fileUploadProgress) / totalSize);
        progressUpdateListener.onProgressUpdate(progress);// your progress % here
    }
    outputStream.flush();
    inputStream.close();
    writer.append(LINE_FEED);
    writer.flush();
}

РЕДАКТИРОВАТЬ

public class UploadFileToServer {

    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;
    private ProgressUpdateListener progressUpdateListener;
    private Context context;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL requestURL
     * @param charset    charset
     * @param boundary   boundary
     * @throws IOException ioException
     */
    public UploadFileToServer(Context context, String requestURL, String charset, String boundary, ProgressUpdateListener progressUpdateListener) throws IOException {
        this.context = context;
        this.charset = charset;
        this.progressUpdateListener = progressUpdateListener;

        // creates a unique boundary based on time stamp
        this.boundary = boundary;
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true);    // indicates POST method
        httpConn.setDoInput(true);
        isCanceled = false;

        httpConn.setRequestProperty("Connection", "Keep-Alive");

        httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
    }

    /**
     * Adds a upload file section to the request
     *
     * @param uploadFile a File to be uploaded
     * @throws IOException ioException
     */
    public void addFilePart(File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--").append(boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"").append(fileName).append("\"")
                .append(LINE_FEED);
        writer.append("Content-Type: " + "application/octet-stream")
                .append(LINE_FEED);
//        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        float bytesWritten = 0;
        int totalSize = (int) uploadFile.length();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
            bytesWritten += bytesRead;
            int progress = (int) ((bytesWritten * fileUploadProgress) / totalSize);
            progressUpdateListener.onProgressUpdate(progress);
        }
        outputStream.flush();
        inputStream.close();
        writer.append(LINE_FEED);
        writer.flush();
    }


    public interface ProgressUpdateListener {
        void onProgressUpdate(int progress);
    }
}

теперь вы можете назвать этот класс следующим образом,

UploadFileToServer uploadFileToServer = new UploadFileToServer(context, url, "UTF_8", boundary,
                                    new UploadFileToServer.ProgressUpdateListener() {
   @Override
   public void onProgressUpdate(int progress) {
       Log.e("Progress", "onProgressUpdate: " + progress );                                    
     }
  });

uploadFileToServer.addFilePart(new File(filePath));
...