laravel + dropzone file not uploading - php

Why is it the file i upload not reflecting on the request even though the file is uploaded successfully?
HTML
<div id="upload_excel" class="dropzone form-control">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
JS
var baseUrl = "{{ url('/') }}";
var token = "{{ Session::getToken() }}";
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#upload_excel", {
paramName: "file",
acceptedFiles: ".xls,.xlsx",
maxFiles: 1,
maxFilesize: 10,
url: baseUrl + "/upload",
params: {
_token: token
}
});
Controller
class UploadsController extends Controller
{
public function upload(Request $request) {
return $file = $request->all();
}
}
Request Preview
[
Request Response
{"_token":"ePssa9sPZxTcRR0Q4Q8EwWKjODXQ8YpCcH8H9wRP","upload_date":"2016-08-02","file":{}}
Did i miss something or what?

I have a controller like this
public function upload(Request $request) {
// validation etc
// ...
// I have a table and therefore model to list all excels
$excelfile = ExcelFile::fromForm($request->file('file'));
// return whater ...
}
In my ExcelFile Model
protected $baseDir = 'uploads/excels';
public static function fromForm(UploadedFile $file) {
$excelfile = new static;
$name = time() . $file->getClientOriginalName();
$name = preg_replace('/\s+/', '', $name);
$excelfile->path = $excelfile->baseDir . '/' . $name;
$file->move($excelfile->baseDir, $name);
return $excelfile;
}
You will also need to add UploadedFile in your Model
use symfony\Component\HttpFoundation\File\UploadedFile;
My dropzone is defined like this to ensure correct token handling
<form action="/users/{{ $id }}/media/excelupload" id="drop-zone" class="dz dropzone">
{{ csrf_field() }}
</form>
<script>
new Dropzone("#drop-zone", {
maxFilesize: 3, // MB
maxFiles: 10,
dictDefaultMessage: "Upload Excel.",
init: function() {
var known = false;
this.on("success", function(file, responseText) {
// do stuff
});
this.on('error', function() {
// aler stuff
});
this.on("addedfile", function() {
if (this.files[10]!=null){
this.removeFile(this.files[0]);
if (known === false) {
alert('Max. 10 Uploads!')
known = true;
}
}
});
}
});
</script>
I hope this helps

Related

"Call to a member function store() on array" When Uploading a File using Laravel 8 with Jetstream - Vue & Intertia.js

I am having a problem uploading an image from a from a form in a vue file. I tried several ways to do this but it seems the file is not properly being set.
I have set "enctype="multipart/form-data" in my form tag
Here is my input element:
<input
#change="onFileChange"
type="file"
accept="image/*"
class="form-control"
name="file"
id="file"
aria-describedby="helpId"
placeholder="Upload a file"
/>
Here is my data objetcs and methods that send the data:
data() {
return {
editMode: false,
professionaldevelopmentitems: [],
professionaldevelopmentitem: {
domain: 1,
domaincategory: 1,
title: "",
dateofpd: "",
location: "",
lengthofpd: "",
facilitatorname: "",
facilitatorcredentials: "",
reflection: "",
file: "",
},
};
},
methods: {
onFileChange(e) {
alert(e.target.files[0]);
alert(e.target.files[0].name);
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.professionaldevelopmentitem.file = e.target.files[0];
alert(this.professionaldevelopmentitem.file);
},
async addProfessionalDevelopmentItem() {
document.getElementById("pdForm").reset();
this.editMode = false;
const res = await axios.post(
"/api/professionaldevelopmentitems",
this.professionaldevelopmentitem
);
if (res.status === 201) {
Toast.fire({
icon: "success",
title: res.data,
});
document.getElementById("pdForm").reset();
$("#manageProfessionalDevelopmentItem").modal("hide");
Fire.$emit("modifiedPDItem");
}
},
async editProfessionalDevelopmentItem(data) {
this.professionaldevelopmentitem = Object.assign({}, data);
this.editMode = true;
},
async updateProfessionalDevelopmentItems(data) {
const res = await axios.put(
`/api/professionaldevelopmentitems/${data.id}`,
this.professionaldevelopmentitem
);
if (res.status === 200) {
Toast.fire({
icon: "success",
title: res.data,
});
document.getElementById("pdForm").reset();
$("#manageProfessionalDevelopmentItem").modal("hide");
Fire.$emit("modifiedPDItem");
this.editMode = false;
}
},
I receive data in my controller and try to store the file:
public function update(Request $request, $id)
{
dd($request->all());
$this->validate($request, [
'title' => ['required'],
'dateofpd' => ['required'],
'lengthofpd' => ['required'],
'location' => ['required']
]);
$path = $request->file('filename')->store('uploads');
$pditem = ProfessionalDevelopmentItem::find($id);
$pditem->domain = $request->domain;
$pditem->domaincategory = $request->domaincategory;
$pditem->title = $request->title;
$pditem->dateofpd = $request->dateofpd;
$pditem->lengthofpd = $request->lengthofpd;
$pditem->location = $request->location;
$pditem->facilitatorname = $request->facilitatorname;
$pditem->facilitatorcredentials = $request->facilitatorcredentials;
$pditem->certificategranted = $request->certificategranted;
$pditem->certificateexpires = $request->certificateexpires;
$pditem->certificateexpiration = $request->certificateexpiration;
$pditem->reflection = $request->reflection;
$pditem->nameofinstitution = $request->nameofinstitution;
$pditem->coursename = $request->coursename;
$pditem->coursecode = $request->coursecode;
$pditem->hoursofinstruction = $request->hoursofinstruction;
$pditem->creditgranted = $request->creditgranted;
$pditem->bookname = $request->bookname;
$pditem->bookauthor = $request->bookauthor;
$pditem->bookyear = $request->bookyear;
$pditem->bookpublisher = $request->bookpublisher;
$pditem->otherdescription = $request->otherdescription;
$pditem->filename = $path;
$pditem->save();
return response('Successfully Updated the Professional Development Item.', 200);
}
the response back is an error on the line when it tries to store the file:
"message": "Call to a member function store() on array",
"exception": "Error",
Any thoughts on what I am dong wrong would be appreciated.
Try sending the uploaded file within FormData. Define a method in the Vue component to prepare the FormData with all data you want to send via ajax to the server
prepareFormData() {
let data = new FormData;
Object.keys(this.professionaldevelopmentitem).forEach(
key => data.append(key, this.professionaldevelopmentitem[key]
);
return data;
}
Then use this method to get the FormData and send it as data to the server in addProfessionalDeveloomentItem and updataProfessionalDevelopmentItems
async addProfessionalDevelopmentItem() {
document.getElementById("pdForm").reset();
this.editMode = false;
const res = await axios.post(
"/api/professionaldevelopmentitems",
this.prepareFormData()
);
if (res.status === 201) {
Toast.fire({
icon: "success",
title: res.data,
});
document.getElementById("pdForm").reset();
$("#manageProfessionalDevelopmentItem").modal("hide");
Fire.$emit("modifiedPDItem");
}
},
async updateProfessionalDevelopmentItems(data) {
const res = await axios.put(
`/api/professionaldevelopmentitems/${data.id}`,
this.prepareFormData()
);
if (res.status === 200) {
Toast.fire({
icon: "success",
title: res.data,
});
document.getElementById("pdForm").reset();
$("#manageProfessionalDevelopmentItem").modal("hide");
Fire.$emit("modifiedPDItem");
this.editMode = false;
}
}
Then you should get the uploaded file in the $request under key file $request->file('file')
This error means that $request->file('filename') returns array. In our case it's because we allowed users to submit 2 files at once:
<form action="/upload" method="post" enctype="multipart/form-data">
#csrf
<input type="file" name="filename[]"><br>
<input type="file" name="filename[]"><br>
<input type="submit">
</form>
To fix this in Laravel 9 we added the type check of the variable in the controller's method:
public function upload(Request $request)
{
$file = $request->file('filename');
if (is_array($file)) {
foreach ($file as $item) {
$item->store('uploads');
}
} else {
$file->store('uploads');
}
// ...
}

Laravel uploading file with chunk and getting FileException error

i'm trying to use pionl/laravel-chunk-upload and Resumable.js to upload large file into server
i implemented view, controller and route and now when i try to upload file i get this error:
Symfony\Component\HttpFoundation\File\Exception\FileException: The
file "XXXXXXXX" was not uploaded due to an unknown error. in file
C:\xampp\htdocs\XXX\vendor\symfony\http-foundation\File\UploadedFile.php
on line 213
and i can't fix this error:
view:
<div class="form-group">
<div class="resumable-error">
Your browser, unfortunately, is not supported by Resumable.js. The library requires support for the HTML5 File API along with file slicing.
</div>
<div class="resumable-drop">
Drop video files here to upload or <a class="resumable-browse"><u>select from your computer</u></a>
</div>
<div class="resumable-progress">
<table>
<tr>
<td style="width: 100%"><div class="progress-container"><div class="progress-bar"></div></div></td>
<td class="progress-text" nowrap="nowrap"></td>
<td class="progress-pause" nowrap="nowrap">
<img src="/assets/global_assets/images/icons/resume.png" title="Resume upload" />
<img src="/assets/global_assets/images/icons/pause.png" title="Pause upload" />
<img src="/assets/global_assets/images/icons/cancel.png" title="Cancel upload" />
</td>
</tr>
</table>
</div>
<ul class="nav nav-sidebar mb-2 resumable-list p-0 pl-3 m-0" data-nav-type="accordion"></ul>
</div>
<script>
var r = new Resumable({
target: '/panel/uploadRadioChannelFile',
chunkSize: 1 * 1024 * 1024,
testChunks: false,
throttleProgressCallbacks: 1,
headers:{
'X-CSRF-Token' :"{{ csrf_token() }}"
},
query:{
_token : "{{ csrf_token() }}"
}
});
// Resumable.js isn't supported, fall back on a different method
if (!r.support) {
$('.resumable-error').show();
} else {
// Show a place for dropping/selecting files
$('.resumable-drop').show();
r.assignDrop($('.resumable-drop')[0]);
r.assignBrowse($('.resumable-browse')[0]);
// Handle file add event
r.on('fileAdded', function (file) {
// Show progress pabr
$('.resumable-progress, .resumable-list').show();
// Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show();
// Add the file to the list
$('.resumable-list').append('<li class="nav-item resumable-file-' + file.uniqueIdentifier + '">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-name').html(file.fileName);
// Actually start the upload
r.upload();
});
r.on('pause', function () {
// Show resume, hide pause
$('.resumable-progress .progress-resume-link').show();
$('.resumable-progress .progress-pause-link').hide();
});
r.on('complete', function () {
// Hide pause/resume when the upload has completed
$('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide();
});
r.on('fileSuccess', function (file, message) {
// Reflect that the file upload has completed
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(completed)');
});
r.on('fileError', function (file, message) {
// Reflect that the file upload has resulted in error
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(file could not be uploaded: ' + message + ')');
});
r.on('fileProgress', function (file) {
// Handle progress for both the file and the overall upload
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html(Math.floor(file.progress() * 100) + '%');
$('.progress-bar').css({width: Math.floor(r.progress() * 100) + '%'});
});
r.on('cancel', function () {
$('.resumable-file-progress').html('canceled');
});
r.on('uploadStart', function () {
// Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show();
});
}
</script>
route:
Route::post('uploadRadioChannelFile', 'UploadController#upload');
and controller:
class UploadController extends Controller
{
public function upload(Request $request)
{
try {
$receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
if ($receiver->isUploaded() === false) {
return response()->json([
"done" => '',
'status' => false
]);
}
$save = $receiver->receive();
if ($save->isFinished()) {
return $this->saveFile($save->getFile());
}
$handler = $save->handler();
return response()->json([
"done" => $handler->getPercentageDone(),
'status' => true
]);
} catch (UploadFailedException $e) {
}
}
protected function saveFile(UploadedFile $file)
{
$fileName = $this->createFilename($file);
//$mime = str_replace('/', '-', $file->getMimeType());
$dateFolder = Carbon::now()->year;
$public_html = config('app.public_path');
$filePath = "upload/{$dateFolder}/";
$file->move($public_html.$filePath, $fileName);
return response()->json([
'path' => $filePath,
'name' => $fileName,
'ffff' => $file->getClientOriginalName(),
]);
}
protected function createFilename(UploadedFile $file)
{
//$extension = $file->getClientOriginalExtension();
//$filename = str_replace("." . $extension, "", $file->getClientOriginalName()); // Filename without extension
//$filename .= "_" . md5(time()) . "." . $extension;
return time() . '.' . $file->getClientOriginalExtension();
}
}

Laravel Vue Dropzone.js request file return NULL

I have a problem, and I can't fix it. I read a lots of forum and issues, but it don't resolve.
The problem is that
$photos = $request->file('file');
return var_dump($photos);
bring NULL. I tried to find the error, but I can't
I want store images on server and in a table, then it connecting to an another products table,
First write in the inputs some data ex. Name,Category, after an other tab upload the images with Dropzone, and save it in one time together.
I am use rowanwins dropzone.
My ... .blade.php
<form method="POST" enctype="multipart/form-data" action="{{ route('product.createnew') }}">
// Other Products inputs ..
//Uploads
<vue-dropzone
ref="myVueDropzone"
id="dropzone"
:options="dropzoneOptions">
</vue-dropzone>
// / form and scripts section
<script>
var url = "{{ route('product.createnew') }}";
console.log(url);
var app = new Vue({
el: '#app',
data: function () {
return {
dropzoneOptions: {
url: url,
thumbnailWidth: 150,
maxFilesize: 2,
maxFiles: 2,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
autoDiscover : true,
clickable : true,
uploadMultiple :true,
addRemoveLinks:true,
headers: {
"X-CSRF-TOKEN": document.head.querySelector("[name=csrf-token]").content
},
},
radioButton: '0',
}
},
methods: {
deleteDropFile(index) {
this.dropFiles.splice(index, 1)
},
}
});
My Create Controller
public function create(Request $request)
{
$validator = Validator::make($request->all(), [
//Other products input
'file' => 'nullable|mimes:jpeg,jpg,png,gif|max:2048',
]);
//$products = new Products
//$products->save();
$photos = $request->file('file');
return var_dump($photos);
if (!is_array($photos)) {
$photos = [$photos];
}
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$savename = sha1(time() . '.' . $request->get('name'))."_$i";
$images = new ProductImages ([
'name' => $request->get('name'),
'post_id'=> $products->id,
'path'=> public_path('uploads') . '/' . $savename,
'main'=> 0,
]);
$images->save();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save(public_path('uploads'). '/' . $savename);
$photo->move(public_path('uploads'), $savename);
}
return redirect()->back();
}
My routes
Route::group(['prefix' => 'product'], function () {
Route::get('/create', 'ProductController#index')->name('product.create'); //View
Route::post('/createnew', 'ProductController#create')->name('product.createnew'); //Post
});
After all I found what is wrong.
It is the validation
'file' => 'nullable|mimes:jpeg,jpg,png,gif|max:2048',
throw the error.
Thanks

Dropzone.js post request in laravel 5.4

I am not receiving any request at controller's uploadGallery method. Although, the post request is received correctly.
gallery.blade.php
<div class="row">
<form action="{{ url('file-upload') }}" method="post" class="dropzone" id="my-awesome-dropzone">
{{ csrf_field() }}
<div class="dz-message">
<h3>Drop images here or click to upload.</h3>
</div>
</form>
</div>
<script type="text/javascript">
$(function (){
Dropzone.options.myAwesomeDropzone = {
paramName: "files",
uploadMultiple:true,
maxFilesize:6,
autoProcessQueue: true,
uploadMultiple: true,
addRemoveLinks: true,
acceptedFiles: ".png, .jpg, .jpeg",
dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",
dictRemoveFile: "Remove",
dictFileTooBig:"Image is bigger than 6MB",
accept: function(file, done) {
console.log("Uploaded");
done();
},
init:function() {
/* var submitButton = document.querySelector('#submit-all')
myAwesomeDropzone = this;
submitButton.addEventListener("click", function(
myAwesomeDropzone.processQueue();
));
this.on("addedfile", function(){
$('#submit-all').show();
});*/
},
success: function(file,done){
console.log("All files done!");
}
}
});
</script>
web.php
Route::get('/gallery', 'PagesController#Gallery');
Route::post('/file-upload', 'ImagesController#uploadImages');
ImagesController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ImagesController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function uploadImages(Image $request) {
$images = request()->file('files');
dd($images);
return view('Gallery');
}
}
Anything inside the uploadImages function is not running. Why?
You have wrong type hinting in your uploadImages() function.
Change your uploadImages() from
public function uploadImages(Image $request)
to
public function uploadImages(Request $request)
Now you should be able to use request() to grab files.
Change this
public function uploadImages(Image $request) {
$images = request()->file('files');
dd($images);
return view('Gallery');
}
to and replace request() with $request since your using eloquent.
public function uploadImages(Request $request) {
$images = $request->file('files');
dd($images);
return view('Gallery');
}
For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications

Get File Input Value in Laravel Via AngularJS form

I want to get value from file input from angularjs form in laravel, but i can't get the value.
why?
angularjs:
<div ng-controller="UploadImgController" >
<div ng-repeat="image in images">
<img ng-src="{{image.image}}" />
</div>
<form ng-submit="uploadImg()" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="path" id="path" ng-model="addimages.path" accept="image/*" app-filereader>
<input type="text" name="propertyid" ng-model="addimages.propertyid">
<input type="submit" value="Upload Image" name="submit" class="btn btn-primary" >
</form>
</div>
laravel (UploadImgController.php):
public function store()
{
$file = Input::file('path');
echo "file: ".$file;
}
(routes.php):
Route::resource('img','UploadImgController');
I got no value. What should I do? Thank you. :)
I recommend using ng-file-upload.
View
<button ng-file-select ng-model="myFiles" ng-file-change="upload($files)">Upload</button>
Angular JS
var app = angular.module('fileUpload', ['angularFileUpload']);
app.controller('MyCtrl', ['$scope', '$upload', function ($scope, $upload) {
$scope.upload = function (files) {
if (files && files.length){
for (var i = files.length - 1; i >= 0; i--) {
var file = files[i];
$upload.upload({
url: '/upload',
fields: {key: 'value'},
file: file
})
.progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('File upload ' + progressPercentage + "% complete.");
})
.success(function (data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
console.log(data);
});
}
}
};
}
]);
Laravel Route
Route::post('upload', [
'uses' => 'FileUploadController#upload'
]);
Laravel Controller
public function upload() {
$file = \Input::file('file');
return $file;
}
You can pull that off without a plugin actually. I did face a similar problem once and this is how I went about it.
View
<input type="file" name="file" onchange="angular.element(this).scope().uploadImage(this.files)"/>
Angularjs Controller
$scope.uploadavtar = function (files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("/upload-url" + $scope.school.profile.id, fd, {
withCredentials: true,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).then(function successCallback(response) {
$scope.result = response;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
console.log(response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
Routes.php
Route::post('/upload-url', 'UsersController#uploadFile');
Laravel Controller
// Upload files
public function uploadFile(Requests\UpdateuploadfileRequest $request, $id)
{
$extension = Input::file('file')->getClientOriginalExtension();
$fileName = time().'.'.$extension; // renameing image
$destination = 'uploads/img'. $fileName;
move_uploaded_file($_FILES['file']['tmp_name'], $destination);
}
}
Request validation file (UpdateuploadfileRequest.php)
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
];
return $rules;
}

Categories