I am writing an API using Laravel 6 and am having some issues with uploading files, in fact, uploading any files at all.
I'm using Postman to test the API. In the params section, i put in a name, and then over in the body (form-data) section, I enter the key filename and then attach a file.
When i send the request, it comes back with the all good status, but it doesn't upload the file, or save the details to the database.
Also, if i dont attach a image file, the validator comes back with the required status, but if i change that to a txt file, it doesn't say anything and comes back with the all good status, so it seems to be missing the filename.* part and only running the first filename validation.
namespace App\Http\Controllers;
use App\ImageUpload;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
class ImageUploadController extends Controller
{
public function store(Request $request): JsonResponse
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'filename' => 'required',
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->fails()) {
return response()->json(['error validation failed'], 400);
}
if ($request->hasFile('filename')) {
foreach ($request->file('filename') as $image) {
$fileName = time().'.'.$image->getClientOriginalExtension();
$image->move(public_path() . '/uploads', $fileName);
$imageUpload = new ImageUpload();
$imageUpload->name = $request->name;
$imageUpload->filename = $fileName
$imageUpload->save();
}
}
return response()->json(['All good'], 200);
}
}
if i dd($resposne) at the very top, the file im trying to upload is there, see below;
+files: Symfony\Component\HttpFoundation\FileBag {#59
#parameters: array:1 [
"filename" => Symfony\Component\HttpFoundation\File\UploadedFile {#44
-test: false
-originalName: "23367298-7883819-image-m-101_1578974555854.jpg"
-mimeType: "image/jpeg"
-error: 0
path: "/tmp"
filename: "phpAJtgNw"
basename: "phpAJtgNw"
pathname: "/tmp/phpAJtgNw"
extension: ""
realPath: "/tmp/phpAJtgNw"
aTime: 2020-01-27 08:59:12
mTime: 2020-01-27 08:59:12
cTime: 2020-01-27 08:59:12
inode: 266560
size: 96981
perms: 0100600
owner: 1000
group: 1000
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
]
}
$requesthas multiple files and in HTML formfilename[]as array.