当前位置:首页 > Web开发 > 正文

‘data‘ = $data ]);} 3、编写路由 // 文件上传 Route::post(‘upload‘

2024-03-31 Web开发

1、首先先在laravel根目录下执行 $ php artisan storage:link ,孕育产生映射文件 

技术图片

2、编写controller层

// 文件上传 public function upload(Request $request){ // 判断是否有上传文件字段 if ( $request->file() ){ //界说一个空数组存放文件列表 $files = []; // 循环获取所有文件字段 foreach ($request->allFiles() as $file){ // 界说一个空数组,便利与储存其它字段 $obj = []; //将图片存储到了 ../storage/app/public/product/ 路径下 $path = $file->store(‘public/product/‘.date(‘Y-m-d‘)); $path = str_replace(‘public‘,‘‘,$path); $obj[‘url‘]= asset(‘storage‘.$path); // 赋值给东西 $files[] = $obj; } return $this->responseMsg( 0, ‘success‘, $files); }else{ return $this->responseMsg( -2, ‘请上传文件‘, null); } } // 通用的返回格局 public function responseMsg($code, $msg, $data){ return response()->json([ ‘code‘ => $code, // 0:告成,,-1:未登录,-2:错误 ‘msg‘ => $msg, ‘data‘ => $data ]); }

3、编写路由

// 文件上传 Route::post(‘upload‘, ‘[email protected]‘);

4、用 postman 模拟请求,注意红框部分,必需要两个不一样的字段才华孕育产生两个文件

技术图片

5、检察 ./storage/app/public/ 文件夹

技术图片

6、 前端代码实现,使用框架为 axios

var formData = new FormData() for (let i = 0; i < _self.previewUrl.length; i++) { // _self.previewUrl 为一个数组,格局:[{file: FileObject}],file字段的值为单个文件的东西 formData.append(‘file‘+i, _self.previewUrl[i].file); } this.axios.post(‘/upload‘, formData, { headers:{ "Content-Type":"multipart/form-data" } }).then((res)=>{ console.log(res.data); });

laravel框架多文件上传

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/33234.html