java - 使用 POST 请求未正确上传文件
问题描述
我正在尝试使用 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";
}}
难道我做错了什么?以这种方式上传文件的另一种方法是什么?
使用Insomnia我可以发送文件,并且 Content-Type 也是“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;
}
}
}
推荐阅读
- c# - C#类继承、接口和实例化
- python - Python Flask API - 发布和接收字节数组和元数据
- apache-kafka - 如何将 Avro 事件推送到 Memsql
- powershell - Terraform GCP:在创建时在 Windows 实例中运行 PowerShell
- sql - 如何选择没有冗余值的 SQL 连接表
- android - 房间得到 ConcurrentModificationException
- git - 更改原点后的 Git 提交分支
- python - 如何在 python 中使用 c++ 库?
- c++ - RestoreFile 调用(文件管理 API - fmapi.dll)返回无效句柄
- c++ - 如何过滤所选目录中的图像文件(在 listWidget 内)