Php 使用改型2.0进行多文件上载
我目前正在开发应用程序的一部分,用户需要从gallery中选择一些图像,然后将这些图像上传到服务器。对于上传,我使用的是使用multipart的改型2.0 根据资源,我成功地实现了它,只使用了一个文件,但我希望在一个会话中,所有用户选择的图像都上传到服务器 环顾四周,我发现它在@partmap annotation上讨论了什么,它似乎是正确的匹配,但是我不明白我将如何迭代我需要上传的图像 有人能告诉我正确的实现方法吗 还检查了: 1.Php 使用改型2.0进行多文件上载,php,android,file-upload,multipart,retrofit2,Php,Android,File Upload,Multipart,Retrofit2,我目前正在开发应用程序的一部分,用户需要从gallery中选择一些图像,然后将这些图像上传到服务器。对于上传,我使用的是使用multipart的改型2.0 根据资源,我成功地实现了它,只使用了一个文件,但我希望在一个会话中,所有用户选择的图像都上传到服务器 环顾四周,我发现它在@partmap annotation上讨论了什么,它似乎是正确的匹配,但是我不明白我将如何迭代我需要上传的图像 有人能告诉我正确的实现方法吗 还检查了: 1. 2.我只是想解决一个类似的问题,但我有大量的文件 我尝试使用
2.我只是想解决一个类似的问题,但我有大量的文件 我尝试使用循环来解决它:
recordsDirectory.mkdirs();
final File[] list_files = recordsDirectory.listFiles();
int cont = list_files.length;
for (int i = 0; i < cont; i++) {
final File ref_file = list_files[i];
String source_filepath = ref_file.getPath();
RequestBody requestBody =
RequestBody.create(MediaType.parse("multipart/form-data"), ref_file);
Call<DeliveryResponse> call = apiService.upload(requestBody, description);
call.enqueue(new Callback<DeliveryResponse>() {
@Override
public void onResponse(Response<DeliveryResponse> response, Retrofit retrofit) {
Log.v(TAG, "[" + TAG + "] Upload success. status: " + response.toString());
DeliveryResponse deliveryResponse = response.body();
Log.v(TAG, "response code: " + deliveryResponse.mStatus);
Log.v(TAG, "response code: " + response.code());
Log.v(TAG, "ref_file: " + ref_file.getPath());
if (response.isSuccess()) {
Log.i(TAG, "[" + TAG + "] The server has response with a status distinct to 200.");
}
else {
if (deliveryResponse.mStatus == 1) {
Log.i(TAG, "[" + TAG + "] The server has response with 1 as status.");
boolean deleted = ref_file.delete();
} else {
Log.i(TAG, "[" + TAG + "] The server has response with 0 as status.");
}
}
}
@Override
public void onFailure(Throwable t) {
Log.e("Upload", t.getMessage());
}
});
}
/***********************************************
RETROFIT API
************************************************/
public interface MyApiEndpointInterface {
@Multipart
@POST("/elderbask/api/sensors/accelerometer")
Call<DeliveryResponse> upload(
@Part("myfile\"; filename=\"image.png\" ") RequestBody file,
@Part("description") String description
);
}
public static class DeliveryResponse {
@SerializedName("status")
int mStatus;
public DeliveryResponse(int status) {
this.mStatus = status;
}
public String toString(){
return "mStatus: " + this.mStatus;
}
}
recordsDirectory.mkdirs();
最终文件[]列表文件=记录目录.listFiles();
int cont=list_files.length;
对于(int i=0;i
但是这个解决方案并没有我期望的那么好。我有很多超时异常,错误的硬编码文件名非常糟糕。由于我没有通过改型解决问题,我最终使用okhttp库提供了我所需要的,下面是一个我使用的代码示例,我希望可以帮助别人 构建请求主体:
okhttp3.RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addPart(okhttp3.Headers.of("Content-Disposition:", "form-data; name=\"myfile\"; filename=\"image" + ImageNumber + ".jpg\""),
okhttp3.RequestBody.create(MEDIA_TYPE_JPG, new File(ImagePath)))
.build();
准备请求:
request = new okhttp3.Request.Builder()
.header("Authorization", "Client-ID " )
.url(YOUR URL)
.post(requestBody)
.build();
启动与服务器的连接:
try {
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
哇!是我做的,你可以像我一样尝试(改装2)
//1.我们需要从服务器获得什么(upload.php脚本)
来自服务器的公共类{
字符串结果;
}
//2.哪个接口可以与upload.php脚本进行通信?
公共接口服务器API{
@多部分
@POST(“upload.php”)//我们的目标php脚本
呼叫上传(
@部分(“文件名”)字符串文件名,
@部分(“文件”)请求主体文件);
改装=
新的改型.Builder()
.baseUrl(“http://192.168.43.135/retro/“”//记住以结尾/
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//3.如何上传
私有无效上载(){
ServerAPI=ServerAPI.reformation.create(ServerAPI.class);
来自_phone=FileUtils.getFile(Environment.getExternalStorageDirectory()+“/aa.jpg”);//org.apache.commons.io.FileUtils的文件
RequestBody to_server=RequestBody.create(MediaType.parse(“多部分/表单数据”),来自_phone);
upload(从_phone.getName()上传到_server.enqueue(新回调()中){
@凌驾
公共void onResponse(调用、响应){
Toast.makeText(MainActivity.this,response.body().get(0).result,Toast.LENGTH_SHORT).show();
}
@凌驾
public void onFailure(Call,Throwable t){}
});
}
//4.upload.php
我最后做的是使用okhttp库,而不是改型,因为它没有提供我所需要的。请尝试此操作。此操作不适用于多个文件
//1. What We Need From Server ( upload.php Script )
public class FromServer {
String result;
}
//2. Which Interface To Communicate Our upload.php Script?
public interface ServerAPI {
@Multipart
@POST("upload.php")//Our Destination PHP Script
Call<List<FromServer>> upload(
@Part("file_name") String file_name,
@Part("file") RequestBody file);
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://192.168.43.135/retro/") // REMEMBER TO END with /
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//3. How To Upload
private void upload(){
ServerAPI api = ServerAPI.retrofit.create(ServerAPI.class);
File from_phone = FileUtils.getFile(Environment.getExternalStorageDirectory()+"/aa.jpg"); //org.apache.commons.io.FileUtils
RequestBody to_server = RequestBody.create(MediaType.parse("multipart/form-data"), from_phone);
api.upload(from_phone.getName(),to_server).enqueue(new Callback<List<FromServer>>() {
@Override
public void onResponse(Call<List<FromServer>> call, Response<List<FromServer>> response) {
Toast.makeText(MainActivity.this, response.body().get(0).result, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<List<FromServer>> call, Throwable t) { }
});
}
//4. upload.php
<?php
$pic = $_POST['file_name'];
$pic = str_replace("\"", "", $pic); //REMOVE " from file name
$f = fopen($pic, "w");
fwrite($f,$_POST['file']);
fclose($f);
$arr[] = array("result"=>"Done");
print(json_encode($arr));
?>