Laravel通过API上传多个图像

loading...


0

我是第一次创建API时创建媒体API .

我有这个代码:

/**
* Store a newly created resource in storage.
*
* @param  \App\Http\Requests\UploadRequest $request
* @return \Illuminate\Http\Response
*/
public function store(UploadRequest $request)
{
    if(!$request->hasFile('fileName')) {
        return response()->json(['upload_file_not_found'], 400);
    }
    $file = $request->file('fileName');
    if(!$file->isValid()) {
        return response()->json(['invalid_file_upload'], 400);
    } 

    if($request->hasfile('fileName'))
    {
        $media = new Media();
        $data = array();
        foreach($request->file('fileName') as $image)
        {
            $rdm = uniqid(5);
            $name= $rdm .'-'.$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;

        }

        $media->fileName = json_encode($data);
        $media->clientId = $request->clientId;
        $media->uploadedBy = Auth::user()->id;
        $media->save();

    }

    return ["success" => "Your media file has been successfully uploaded"];
}

请问您为什么不将图像上传到公共路径 . 它也不会在数据库中存储任何内容 . 我在发送POST请求时从postman获得了200个代码,但是数据库有一个空数组作为fileName?

编辑

我上传了多张图片 . 没有一个表格,因为我正在为移动应用程序制作api . 该请求是对URL / api / v1 / media的POST请求

loading...

2回答

  • -1

    发送为api的二进制文件 .

    php file_get_contents


  • 0

    这是我想出的解决方案:)

    这会上载多个文件并检查扩展名中的有效文件 .

    public function store(UploadRequest $request)
    {
        if(!$request->hasFile('fileName')) {
            return response()->json(['upload_file_not_found'], 400);
        }
    
        $allowedfileExtension=['pdf','jpg','png'];
        $files = $request->file('fileName'); 
        $errors = [];
    
        foreach ($files as $file) {      
    
            $extension = $file->getClientOriginalExtension();
    
            $check = in_array($extension,$allowedfileExtension);
    
            if($check) {
                foreach($request->fileName as $mediaFiles) {
                    $media = new Media();
                    $media_ext = $mediaFiles->getClientOriginalName();
                    $media_no_ext = pathinfo($media_ext, PATHINFO_FILENAME);
                    $mFiles = $media_no_ext . '-' . uniqid() . '.' . $extension;
                    $mediaFiles->move(public_path().'/images/', $mFiles);
                    $media->fileName = $mFiles;
                    $media->clientId = $request->clientId;
                    $media->uploadedBy = Auth::user()->id;
                    $media->save();
                }
            } else {
                return response()->json(['invalid_file_format'], 422);
            }
    
            return response()->json(['file_uploaded'], 200);
    
        }
    }
    
评论

暂时没有评论!