当前位置: 首页 > 知识库问答 >
问题:

用OkHttp上传Android多部分文件

芮歌者
2023-03-14

我正在使用这个音频记录和视频文件,它是工作的,但我想用OKHTTP取代它。我没弄明白。有人能帮我一下吗?

public class HttpMultipartUpload {
    static String lineEnd = "\r\n";
    static String twoHyphens = "--";
    static String boundary = "AaB03x87yxdkjnxvi7";

    public static String upload(URL url, File file, String fileParameterName, HashMap<String, String> parameters)
            throws IOException {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream dis = null;
        FileInputStream fileInputStream = null;

        byte[] buffer;
        int maxBufferSize = 20 * 1024;
        try {
            //------------------ CLIENT REQUEST
            fileInputStream = new FileInputStream(file);

            // open a URL connection to the Servlet
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParameterName
                    + "\"; filename=\"" + file.toString() + "\"" + lineEnd);
            dos.writeBytes("Content-Type: text/xml" + lineEnd);
            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            buffer = new byte[Math.min((int) file.length(), maxBufferSize)];
            int length;
            // read file and write it into form...
            while ((length = fileInputStream.read(buffer)) != -1) {
                dos.write(buffer, 0, length);
            }

            for (String name : parameters.keySet()) {
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(parameters.get(name));
            }

            // send multipart form data necessary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            dos.flush();
        } finally {
            if (fileInputStream != null) fileInputStream.close();
            if (dos != null) dos.close();
        }

        //------------------ read the SERVER RESPONSE
        try {
            dis = new DataInputStream(conn.getInputStream());
            StringBuilder response = new StringBuilder();

            String line;
            while ((line = dis.readLine()) != null) {
                response.append(line).append('\n');
            }

            return response.toString();
        } finally {
            if (dis != null) dis.close();
        }
    }
}

共有1个答案

南门星河
2023-03-14

请参见关于过帐表单数据的文档示例

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/postmultipart.java

    RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "Square Logo")
        .addFormDataPart("image", "logo-square.png",
            RequestBody.create(
                new File("docs/images/logo-square.png"),
                MEDIA_TYPE_PNG))
        .build();

    Request request = new Request.Builder()
        .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
        .url("https://api.imgur.com/3/image")
        .post(requestBody)
        .build();
 类似资料:
  • 在Android中使用OKHTTP以多部分方式上传单个大文件(更具体地说,上传到s3)时,我有什么选择?

  • 由邮递员生成以下代码: 此请求在服务器上生成一个大小为0 Kb的文件。而且我无法放文件。所以,我必须放一个这样的文件: 但我有一个超时选项。 如何使用这种Rest API放置文件?

  • 我试图实现一个进度条来指示一个多部分文件上传的进度。 有人能举个例子说明我会怎么做吗?

  • 我正在Spring controller中努力实现多部分文件上传。我读过很多问题,谷歌,但似乎什么都不管用。 我明白了 我的BE控制器: FE,angularJS: HTML: 还有应用程序。属性包括: 更新: 当我按照@Byeon0gam的建议从我的控制器中删除@RequestParam时,我不再会遇到这个错误,但是我的文件在控制器中是空的。虽然在FE服务中,如我所见,它不是空的:

  • 它应该很简单:我必须发送文件和一些字符串值。但我想不出怎么做。 根据我发现的一些样本,我首先尝试了以下内容: 它给我一个“400错误请求”错误。 我做错了什么? 编辑:顺便说一句,上面的“getfile()”返回一个File对象。其余的参数都是字符串和int。

  • 正如上面的问题所描述的,我正在尝试将一个文件从okhttp3上传到服务器。 我总是收到‘你没有选择一个文件上传’在我的方法从codeIgniter部分。 这是我的代码 Android: 服务器代码: 我做错了什么?谢谢!