我正在使用Android Studio创建一个应用程序,我想将两个带有某些发布参数的图像上传到php服务器。
我尝试关注youtube上的许多视频,从github复制源代码,但是没有任何效果。我认为问题不在于php服务器,因为在iOS应用中上传有效。
这是使用OKHttp库的代码
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File f1 = new File(getPath(uri1img));
String ct1 = getMimeType(f1.getPath());
String fp1 = f1.getAbsolutePath();
File f2 = new File(getPath(uri2img));
String ct2 = getMimeType(f2.getPath());
String fp2 = f2.getAbsolutePath();
MediaType MEDIA_TYPE = MediaType.parse("image/jpg");
fp1.substring(fp1.lastIndexOf("/")+1);
OkHttpClient client = new OkHttpClient();
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("front","img1.jpg", RequestBody.create(MEDIA_TYPE, f1))
.addFormDataPart("back","img2.jpg", RequestBody.create(MEDIA_TYPE, f2))
.addFormDataPart("lang", "en")
.addFormDataPart("name", "test")
.addFormDataPart("surname", "test")
.addFormDataPart("birthdate", "test")
.addFormDataPart("street", "test")
.addFormDataPart("city", "test")
.addFormDataPart("province", "test")
.addFormDataPart("country", "test")
.build();
Request request = new Request.Builder()
.url("http://127.0.0.1/add.php")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("Error : "+response);
}
Log.d("Response", response.toString());
Log.d("fp1", getPath(uri1img));
Log.d("fp2", getPath(uri2img));
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
PHP服务器应响应“确定”,并且它可以正常工作,因为日志显示了该消息,但未加载文件。
2019-09-07 21:46:53.667 24479-25229/com.application D/Response: Response{protocol=http/1.1, code=200, message=OK, url=http://127.0.0.1/add.php}