![](/img/trans.png)
[英]Retrofit2 throws ConnectionShutdownException error while uploading a file using Multipart
[英]Getting a file with “0 bytes on disk” after uploading it using retrofit2
我使用的是我作為學校項目制作的網站的移動版本,該網站本身運行正常,我的后端似乎也正常運行,所以我使用的是相同的PHP文件,我只是在構建前端端側。
我正在使用Retrofit2來使用我的PHP文件,但遇到一個問題,我無法從移動應用正確上傳任何文件,整個數據庫工作正常,但是在上傳文件時出現了問題,即上傳的文件磁盤上有0個字節
1.-我使用意圖從畫廊獲取圖片
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Selecciona las imagenes"), PICK_IMAGE_REQUEST );
onActivityRestult:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
File file = new File(getPathFromURI(getContext(), data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getPathFromURI(getContext(), data.getData()));
multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
}
}
2.-我調用PHP文件
RetrofitInterface retrofitInterface = RetrofitClient.createRetrofit().create(RetrofitInterface.class);
// The first 8 params are for the database stuff, the last param "multipartBody" is the one who doesnt work
Call<RespuestaGenerica> call = retrofitInterface.crearEvento(idUsuario, nombre, descripcion,
domicilio, fecha, entrada, ciudad, result, multipartBody);
call.enqueue(new Callback<RespuestaGenerica>() {
@Override
public void onResponse(Call<RespuestaGenerica> call, Response<RespuestaGenerica> response) {
Log.d(TAG, response.body().toString());
}
@Override
public void onFailure(Call<RespuestaGenerica> call, Throwable t) {
Toast.makeText(getContext(), "Error al crear el evento: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
改造界面:
@Multipart
@POST("conexiones/contenido/eventos/crearEvento.php")
Call<RespuestaGenerica> crearEvento(@Part("idUsuario")String idUsuario, @Part("nombre")String nombre,
@Part("descripcion")String descripcion, @Part("domicilio")String domicilio,
@Part("fecha")String fecha, @Part("entrada")String entrada,
@Part("ciudad")String ciudad, @Part("tags")String tags,
@Part MultipartBody.Part file);
這是我存儲文件的后端功能
function guardarImagenes ($idEvento) {
$cont = 0;
foreach($_FILES as $aux) {
$ext = 'jpg';
$nombreFichero = $cont++ . '.' . $ext; // e.j 0.jpg
$ruta = '../../../media/eventos/'.$idEvento;
if(!is_dir($ruta)) // Make dir if doesnt exists
mkdir($ruta);
$ruta .= '/' . $nombreFichero; // Full route
move_uploaded_file($aux['tmp_name'], $ruta); // Attempt to upload it
}
}
我不知道為什么要上傳磁盤上有0字節的文件,請幫忙! 謝謝c:
該問題可能與使用的媒體類型有關,您可以嘗試:
MediaType.parse(getContentResolver().getType(fileUri))
而不是硬編碼MediaType.parse("multipart/form-data"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.