Android从我的laravel 5.7 API上传图像,但是 $ request-> input('image')始终为空。我也尝试使用邮递员及其工作正常。有人可以帮我吗? XD
使用邮递员表单数据类型的成功结果
if($request->hasFile('image'))
{
$image = $request->file('image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('uploads/messenger');
$image->move($destinationPath, $name);
$path = url('')."/webservices/public/uploads/messenger/".$name;
$result=[
"image_url" => $path,
];
$succes = "1";
$successMessage = "Image uploaded";
$errorMessage = "";
}
else
{
$result = (object) array();
$succes = "0";
$successMessage = "";
$errorMessage = "Image not found";
}
答案 0 :(得分:0)
使用Storage Facades存储文件:
在storage/app/public/uploads/messenger
内创建文件夹:具有777权限
运行命令:php artisan storage:link
以符号链接公用文件夹可用的存储文件夹内容
在您的控制器中:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
public function upload_image(Request $request){
try{
// added validator for image field
$validator = Validator::make($request->all(), [
'image'=>'required|mimes:jpeg,jpg,png,gif|max:5120'
]);
if ($validator->fails()) {
$response=array('status'=>'error','result'=>0,'errors'=>implode(',',$validator->errors()->all()));
return response()->json($response, 200);
}else{
if($request->hasFile('image')){
$uniqueid=uniqid();
$original_name=$request->file('image')->getClientOriginalName();
$size=$request->file('image')->getSize();
$extension=$request->file('image')->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$imagepath=url('/storage/uploads/messenger/'.$filename);
$path=$request->file('image')->storeAs('public/uploads/messenger/',$filename);
$response=array('status'=>'success','result'=>1,'image'=>$imagepath);
return response()->json($response, 200);
}else{
$response=array('status'=>'error','result'=>0,'errors'=>'no image found');
return response()->json($response, 200);
}
}
}catch(\Exception $e){
$response=array('status'=>'error','result'=>0,'errors'=>'Internal Server Error');
return response()->json($response, 500);
}
}
在从客户端像Content-Type : multipart/form-data
或android
上上传图像时添加postman
标头