java - 文件未使用 POST 请求正确上传

标签 java android http-post okhttp

我正在尝试使用 POST 请求从 Android 手机上传 .zip 文件。我通过论坛 okhttp 进行了一些探索,这应该使它变得非常容易。

到达服务器的文件是一个名称正确的 zip 文件,但文件中没有任何内容(为 0kb)。我怀疑通过 okhttp 发送时流没有正确刷新。

public class FileSender extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... params) {
    String zipPath = params[0];
    String zipName = params[1];
    String serverUrl = "http://192.168.1.109:5000"+"/files/"+zipName;
    File file = new File(zipPath+zipName);
    Log.d("File name", "zipName: "+zipName+" file.getName(): "+file.getName());

    // TODO file is not send properly...
    RequestBody postBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(zipName, file.getName(),
                    RequestBody.create(MediaType.parse("application/octet-stream"), file))
            .build();

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(serverUrl)
            .post(postBody)
            // TODO insert API-key here
            .addHeader("API-key", "<my-api-key>")
            .build();


    try {
        Response response = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "Request Submitted";

}}

我基本上用 this 来实现它, this作为模板。

我做错了什么吗?以这种方式上传文件的另一种方法是什么?

使用Insomnia我能够发送文件,内容类型也是“application/octet-stream”。

最佳答案

我设法让它发挥作用。问题出在我的 Flask 服务器端。这是接受文件的代码:

@api.route("/files", methods=["POST"])
def post_file():
    """Upload a file."""
    zipfile = request.files["zip"]
    filename = secure_filename(zipfile.filename)
    # Check if user has correct key
    user_key = request.headers.get("API-key")
    if user_key not in ALLOWED_KEYS:
        return f"Permission denied. Key '{user_key}' has no access.", 401

    if "/" in filename:
        # Return 400 BAD REQUEST
        abort(400, "no subdirectories directories allowed")

    zipfile.save(os.path.join(UPLOAD_DIRECTORY, filename))
    # Before I tried this (which does not work):
    # with open(os.path.join(UPLOAD_DIRECTORY, secure_filename(filename)), "wb") as fp:     
    #     fp.write(request.data)

    # Return 201 CREATED
    return "Successfully uploaded file.", 201

这是我的 Android 端的代码:

public class FileSender extends AsyncTask<String, Boolean, Boolean> {

@Override
protected Boolean doInBackground(String... params) {
    String zipPath = params[0];
    String zipName = params[1];
    // TODO put ip in env-variable
    String serverUrl = "http://IP:Port"+"/files";
    File file = new File(zipPath+zipName);
    Log.d("File name", "zipName: "+zipName+" file.getName(): "+file.getName());
    RequestBody postBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("zip", file.getName(),
                    RequestBody.create(MediaType.parse("application/zip"), file))
            .build();

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(serverUrl)
            .post(postBody)
            // TODO insert API-key here
            .addHeader("API-key", "<API-Key>")
            .build();

    try {
        Response response = client.newCall(request).execute();
        Log.d("SendToServer", "Worked: "+response.body().string());
        return true;
    } catch (IOException e) {
        Log.d("SendToServer", "Error: "+e.toString());
        e.printStackTrace();
        return false;
    }

}

}

关于java - 文件未使用 POST 请求正确上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010644/

相关文章:

java - Camel HTTP 端点 : How to set URL-String to POST Parameter

php - 从 cUrl 读取 PHP 中的 POST 数据

java - Spring Webflux Mono : unable to collect the results as List

java - 我可以查看 Java 序列化对象进行调试吗?

android - 设计 Android 小部件的宽度和高度

android - 大型字符串数组会卡住我的程序吗?

android - 为什么我的 Android 应用程序中有一个 "libs"文件夹?

java - Kraken API - 签名无效

java - 在java中将二维数组转换为List?

java - 具有不可变参数的自引用枚举