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

时间:2020-04-03 11:15:24

标签: 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";

}}

我基本上以thisthis作为模板来实现它。

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

使用Insomnia我可以发送文件,并且Content-Type也是“ application / octet-stream”。

1 个答案:

答案 0 :(得分:0)

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

wget https://releases.hashicorp.com/terraform/0.12.24/terraform_0.12.24_linux_amd64.zip
unzip terraform_0.12.24_linux_amd64.zip
sudo mv terraform_0.12.24_linux_amd64 /usr/local/bin
rm terraform_0.12.24_linux_amd64.zip

这是我的Android端代码:

@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

}