I'm trying to upload an image to the database but no matter what I try I either get this error
Call to a member function getClientOriginalExtension() on null
or it says it saved correctly but it doesn't save anything
The following code is in the vue.js file in the submit function for the form where this the image is being uploaded. This is what I've tried to send the file to the controller
This gives me the error above
if (this.form.file && this.form.imageUrl) {
this.form.file = this.form.imageUrl;
} else {
}
var data = Converter.objectToFormData(this.form);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This also gives me the error above
let data = Object.assign({}, this.form);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This doesn't give me any errors, but nothing gets saved
var data = new FormData();
data.append('question', this.form.question);
data.append('instruction', this.form.instruction);
data.append('survey_section_id', this.form.survey_section_id);
data.append('response_type_id', this.form.response_type_id);
data.append('questionOptions', this.form.questionOptions);
data.append('rank', this.form.rank);
data.append('num', this.form.num);
data.append('show_text', this.form.show_text);
data.append('file', this.form.file);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This is the code in the controller where the error gets triggered
$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
$imageFile = $request->file('file');
$filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
$imageFile->move($destino, $filename);
$preg->image = $destino . '/' . $filename;
}
if I dd($imageFile) it always returns null or false, my guess is that the file isn't being sent as a file but I'm not sure what I'm doing wrong or why this is happening, the $image returns true so it does go into that if statement.
Assuming you have put enctype="multipart/form-data" on your form, there was an error in a laravel 6 that forced me to do this before getting the image:
$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
$size = $request->file('file')->getSize();
$imageFile = $request->file('file');
$filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
$imageFile->move($destino, $filename);
$preg->image = $destino . '/' . $filename;
}
I'm not sure if it gave me the same error, but the file was always null if you didn't get the size before,
Hope it helps!
Related
Here is my function in flutter
I have use multi_image_picker to pick images sand i have save them in that variable images. Now I want post those images in laravel api. But this don't work.
if(images != null ){
try{
List<MultipartFile> allMultiFiles = [];
for (Asset asset in images) {
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
print(imageData);
var multipartFile = new MultipartFile.fromBytes(
imageData,
filename: asset.name,
);
allMultiFiles.add(multipartFile);
}
FormData formData = FormData.fromMap({
'images' : allMultiFiles
});
var response = await dio.post(UPLOAD_URL, data:formData);
if(response.statusCode == 200){
print('done');
}else{
print('not save image. Error !!');
}
}catch (e){
print(e.toString());
}
}
}
Here is my function to store
public function save(Request $request){
if(!$request->hasFile('images')){
return response()->json([
'upload file not found' => 'not found'
],400);
}else{
$allowedExtension = ['jpg','jpeg','png'];
$files = $request->file('images');
$erros = [];
foreach ($files as $file){
$extension = $file->getClientOriginalExtension();
$check = in_array($extension,$allowedExtension);
if($check) {
foreach($request->images as $mediaFiles) {
$path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
return response()->json([
'message' => 'images saved'
],200);
}
} else {
return response()->json(['invalid_file_format'], 422);
}
}
}
}
It not work, images are not saved.
I'm beginner in flutter and thanks for your help.
whenever I uploaded an image in laravel, the image is upload to the database but after database uploading, my image didn't save that image in my root folder,
here is my upload code:
public function store(Request $request)
{
$records = $request->all();
if ($records != '') {
if ($request->session()->has('is_user_logged')) {
$UserPostModel = new UserPostModel;
$UserPostModel->uid = $request->session()->get('uid');
$UserPostModel->uname = $request->session()->get('name');
$UserPostModel->msg = $request->input('status');
$UserPostModel->eid = $request->input('event');
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$fileName = $request->file('image')->getClientOriginalName();
$fileName = time() . "_" . $fileName;
$request->file = move_uploaded_file('uploads',$fileName);
$UserPostModel->image = $fileName;
}
}
$UserPostModel->save();
return redirect('uprofile')->with('message', 'Seccessfully Post !');
} else {
return redirect('login');
}
} else {
return redirect('/uprofile')->with('message', 'Please select image!');
}
}
Use store method and pass the driver as the second argument
$path = $request->file('image')->store($store_path, 'public');
Please replace this code with your image upload condition.
if ($file = $request->file('image')) {
$name = time() . $file->getClientOriginalName();
$file->move('uploads', $name);
$UserPostModel->image = $name;
}
$UserPostModel -> save();
I'm trying to upload and save images with Axios and a Laravel API, but i'm getting a 422 error.
I've tested with Postman and i have the same result, i have a similar controller**(without the Foreach)** but to upload only one image at once and it works fine.
///Axios
async submitFiles(){
let fd = new FormData()
for(var i = 0; i < this.files.length; i++){
let file = this.files[i]
fd.append('photo[' + i + ']', file)
}
try{
await this.$axios.$post(`/albums/${this.$route.params.id}/photos`, fd, {headers:{'Content-Type': 'multipart/form-data'}})
console.log(...fd)
alert('uploaded')
this.files = []
}
catch(err){
console.log(err)
alert(err)
}
}
//Laravel
class PhotosInAlbumController extends Controller
{
public function store(PhotoInAlbumRequest $request, Album $album)
{
if($request->hasfile('photo'))
{
$photo = new PhotoInAlbum();
$photo->photo = $request->photo;
$images[] = $request->file('photo');
foreach ($images as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathInfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('photo/images', $filenameToStore,'public');
$photo->photo = $path;
$album->photos()->save($photo);
}
}
return $photo;
}
}
Hope someone can help me to figure out what's going on.
Thanks in advance (=
First, sorry I can't comment yet. But I see in this line:
$images[] = $request->file('photo');
that a bi-dimensional array is built. I would try the assignment without the brackets:
$images = $request->file('photo');
I am working on multiple file upload code is not showing any error
public function imagenewAction()
{
$form = new ImageNewForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
// die('checko');
if($request->isPost())
{
// die('checko');
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($data);
if ($form->isValid())
{
//New Code
$dataNew=array('','image','image1');
for($i=1;$i<=2;$i++)
{
$addressProof = $data[$dataNew[$i]]['name'];
$addressProofextension = pathinfo($addressProof, PATHINFO_EXTENSION);
// $addressProofimg = $addressProof . $i . "." . $addressProofextension;
$addressProofimg = $addressProof;
//$verificationdocuments->setdocphotocopy($addressProofimg);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
$adapter->addFilter(new \Zend\Filter\File\Rename(array(
'target' => 'public/img/upload',
'overwrite' => true
)), null, $addressProofimg);
if(!$adapter->receive($addressProofimg))
{
print_r ( $adapter->getMessages (), 1 );
}
else
{
echo "Image Uploaded";
}
}
}
}
return array('form' => $form);
}
It is giving blank error messages and not uploading images please help me to get away with this I am stuck from last 2 days
I am trying to use dropzone.js combined with other form elements and everything is working fine except one thing. I have some validation rules for other form elements and when one of the validation rules fails, it sends errors with ajax response. When an error occurs all dropzone files gets cancelled from the queue. Then I need to add dropped files manually again and submit the form. Is there any way to keep all image files in the queue even if an error occurs so that I can try re-sending them again ?
here is my dropzone configuration :
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
addRemoveLinks:true,
This is the method which is called after form submit:
public function save($request)
{
$request = $request->all();
// Create a new validator instance from our validation rules
$validator = Validator::make($request, $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
$this->errors = $validator->errors();
return false;
}
$user_id = getLoggedInId();
$request['operator_id'] = $this->operator->getId($user_id);
$result = $this->visit->add($request);
if ($result == 'updated')
{
$this->success = 'Successfully Updated!';
return $result;
}
elseif ($result == 'failed')
{
$this->errors = 'failed!';
return false;
}
elseif ($result == 'notAllowed')
{
$this->errors = 'Not Allowed to update this record';
return false;
}
else
{
if (Input::file('file'))
{
$visit_id = $result->id;
$files = Input::file('file');
$today = Carbon::now();
$patient_id = Input::get('patient_uid'); //need more validation later on
$center_id = substr($patient_id, 0, 3);
$uid = substr($patient_id, -5);
$upload_dir = $center_id . '/' . $today->year . '/' . $today->month . '/';
foreach ($files as $file)
{
// public/uploads
$response = $this->report->upload($file, $upload_dir, $visit_id, $uid);
if ($response['error'])
{
$this->errors = $response['message'];
return false;
}
}
}
$this->success = trans('patients/visit_form.successfully_created');
return $result;
}
and this is the logic for submitting form:
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0)
{
myDropzone.processQueue();
} else {
submitVisitForm();
}
});