我无法将文件上传到名称中包含空格的服务器。对于名称不带空格的文件,它可以正常工作。这是我的代码:
//this method is invoked when file is selected by file chooser
protected void onActivityResult(int requestCode, int resultCode,
final Intent data) {
if(requestCode == 10 && resultCode == RESULT_OK){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("http://192.168.137.1/cloudserver/save_file.php")
.post(request_body)
.build();
Response response = client.newCall(request).execute();
php代码:
<?php
$file_path = "upload/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)) {
echo "success";
}else {
echo "error";
}
?>
答案 0 :(得分:-1)
好吧,我知道了...通过替换这段代码解决了我的问题
String mimeType= URLConnection.guessContentTypeFromName(f.getName());
RequestBody file_body = RequestBody.create(MediaType.parse(mimeType),f);`