【发布时间】:2019-11-17 00:34:04
【问题描述】:
我正在使用我作为学校项目制作的网站的移动版本,该网站本身运行良好,我的后端似乎也运行良好,所以我使用相同的 PHP 文件,我只是在构建前端。
我正在使用 Retrofit2 来使用我的 PHP 文件,但我遇到了一个问题,我无法从移动应用程序正确上传任何文件,整个数据库工作正常,但是在上传文件时出错了,上传的文件在磁盘上有 0 个字节
1.- 我使用 Intent 从图库中获取图片
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 );
onActivityResult:
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:
【问题讨论】:
标签: java php android retrofit2