使用 POST-请求未正确上传文件
File is not correctly uploaded using POST-request
我正在尝试使用 POST 请求从 Android phone 上传 .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".
我成功了。问题出在我的烧瓶服务器端。这是接受文件的代码:
@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;
}
}
}
我正在尝试使用 POST 请求从 Android phone 上传 .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".
我成功了。问题出在我的烧瓶服务器端。这是接受文件的代码:
@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;
}
}
}