Chunk upload does not work with large files - Laravel 5.8 - ajax

I need to upload large files to my site, and to do this, I used the Dropzone JS, with pion/laravel-chunk-upload, I do not understand, everything is good and true, but although this, any upload for large files is not completed, when uploading small files, I get a result, but When I try with larger files eg 5MB,
It stops at a part of uploading for Hosts eg (Hostinger)
does not work and gives an error from laravel validator for WampServer 4 (localhost)
I tried here to remove my Validator, but the same problem, I can't
upload or check if is a valid file or something like that! (for localhost)
I tried a lot but I do not understand the problem and can't find a solution, please help, this is my code:
My view:
<form action="{{ route('files') }}" enctype="multipart/form-data" class="dropzone" id="fileupload" method="POST">
#csrf
<input type="hidden" name="item_id" value="{{ $item->id }}">
<div class="fallback">
<input name="file" type="files" multiple />
</div>
</form>
Controller:
// UPLOAD FILES
protected function uploadFiles(Request $request) {
$validator = Validator::make($request->all(), [
'file' => 'required|max:3145730', // 3GB
'item_id' => 'required|numeric'
]);
$item_id = $request->item_id;
$item_data = Item::whereId($item_id)->where('user_id', Auth::id())->whereStatus(0)->first();
if (!$item_data || $validator->fails()) {
return response()->json([
'status' => true,
'error' => 'Invalid data!'
], 401);
}
if ($request->hasFile('file')) {
# CHECK IF IS FILE
if ($request->file('file')->isValid()) {
$file = $request->file('file');
# UPLOAD
$type = strtolower($file->getClientOriginalExtension());
$mime = $file->getMimeType();
$size = $file->getSize();
$width = null;
$height = null;
if (!in_array($type, ['png', 'jpeg', 'jpg', 'zip']) || !in_array($mime, ['application/octet-stream', 'application/zip', 'image/jpg', 'image/png', 'image/jpeg'])) {
return response()->json([
'status' => true,
'error' => 'You can\'t upload files of this type.'
], 401);
}
// create the file receiver
$receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
// check if the upload is success, throw exception or return response you need
if ($receiver->isUploaded() === false) {
throw new UploadMissingFileException();
}
// receive the file
$save = $receiver->receive();
// check if the upload has finished (in chunk mode it will send smaller files)
if ($save->isFinished()) {
// save the file and return any response you need, current example uses `move` function. If you are
// not using move, you need to manually delete the file by unlink($save->getFile()->getPathname())
if (in_array($type, ['png', 'jpeg', 'jpg'])) {
list($width, $height) = getimagesize($file);
}
return $this->saveFile($save->getFile(), $item_id, $type, $mime, $size, $width, $height);
}
// we are in chunk mode, lets send the current progress
/** #var AbstractHandler $handler */
$handler = $save->handler();
return response()->json([
"done" => $handler->getPercentageDone(),
'status' => true
]);
}
}
return response()->json([
'status' => true,
'error' => 'Invalid data! Please upload a valid file.'
], 401);
}
JS:
Dropzone.prototype.defaultOptions.dictDefaultMessage = "DRAG & DROP FILES HERE TO UPLOAD";
var myDropzone = new Dropzone("#fileupload", {
acceptedFiles: ".jpg, .jpeg, .png, .zip",
chunking: true,
method: "POST",
maxFilesize: 3072, // 3GB
chunkSize: 10000000, // 10MB
maxFiles: 6,
parallelChunkUploads: true,
});

Check your PHP.ini configuration for max size.
upload_max_filesize = 10M
post_max_size = 11M

Related

How can i change the image upload directory and view image url in laravel

In my script all images uploaded goes into directory "ib" but i want to change that directory to a different name eg. "imgib"
here is what i did so far. i changed the code vlues from "ib" to "imgib"
} else {
// upload path
$path = 'imgib/';
// if path not exists create it
if (!File::exists($path)) {
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
}
// move image to path
$upload = $request->file('uploads')->move($path, $imageName);
// file name
$filename = url($path) . '/' . $imageName;
// method server host
$method = 1;
}
// if image uploded
if ($upload) {
// if user auth get user id
if (Auth::user()) {$userID = Auth::user()->id;} else { $userID = null;}
// create new image data
$data = Image::create([
'user_id' => $userID,
'image_id' => $string,
'image_path' => $filename,
'image_size' => $fileSize,
'method' => $method,
]);
// if image data created
if ($data) {
// success array
$response = array(
'type' => 'success',
'msg' => 'success',
'data' => array('id' => $string),
);
// success response
return response()->json($response);
} else {
if (file_exists('imgib/' . $filename)) {$delete = File::delete('imgib/' . $filename);}
// error response
return response()->json(array(
'type' => 'error',
'errors' => 'Opps !! Error please refresh page and try again.',
));
}
so far everything looks ok and it creates "imgib" directory automatically and all uploads go into "imgib" directory.
But the issue is, image url still uses the same old directory name.
eg. site.org/ib/78huOP09vv
How to make it get the correct url eg. site.org/imgib/78huOP09vv
Thanks for the help everyone. I managed to fix the issue by editing viewimage.blade.php
Yes of course need to clear the browser cache after editing the files.

Handling File uploads and reorder with Laravel Livewire and Filepond

I have a form in my application that allows users to create posts and while doing so upload multiple images to the post being created.
I am using Laravel Livewire and Filepond to achieve this.
The problem I am having is I need to allow the user to reorder the images (as it is a gallery and the order is important), and save the order in the database when the form in submitted.
Another issue I am running into is allowing a user to edit their post later. I need their pre-existing post images loaded in filepond, and also allow them to upload more, delete, and/or reorder.
When the user saves the post I need to be able to update my database and file system.
All info online is how to upload files, but no info on how to reorder, or pre-populate with pre-existing files.
Here is my current code for reference:
<div
x-data=""
x-init="
FilePond.setOptions({
allowMultiple: true,
allowReorder: true,
itemInsertLocation: 'after',
server: {
process: (fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
#this.upload('images', file, load, error, progress)
},
revert: (filename, load) => {
#this.removeUpload('images', filename, load)
},
load: (source, load, error, progress, abort, headers) => {
var myRequest = new Request(source);
fetch(myRequest).then(function(response) {
response.blob().then(function(myBlob) {
load(myBlob)
});
});
},
},
});
const pond = FilePond.create($refs.input, {
acceptedFileTypes: ['image/png', 'image/jpeg'],
maxFileSize: '7MB',
allowImageCrop: true,
allowReorder: true,
allowImageResize: true,
imageResizeTargetWidth: '1000px',
imageResizeTargetHeight: '1000px',
filePosterMaxHeight: '256px',
files: {{ $existingImages }} // used for when editing a post and it already has images. see php component on how I set this variable
});
"
>
<div wire:ignore wire:key="images">
<div class="form-group text-center">
<input
id="image-upload"
type="file"
x-ref="input"
multiple
data-allow-reorder="true"
data-max-file-size="3MB"
data-max-files="10"
>
</div>
</div>
</div>
My Livewire PHP component:
public $images = [];
public $existingImages;
public function mountMedia($post) {
if($post){
$this->existingImages = $post->images->map(function ($image) use ($post) {
return [
'source' => $image->id,
'options' => [
'type' => 'local',
'file' => [
'name' => $image->getUrl(),
'size' => $image->file_size,
'type' => $image->mime_type,
],
'metadata' => [
'poster' => $image->getUrl(),
'position' => $image->position
],
],
];
});
}
}
public function saveImage($file, $post, $position) {
// Create a unique random string
$randString = Str::random(3);
// Get time
$time = time();
// Set file name
$filename = $time. '-' . $randString.'-'.auth()->user()->id;
$extension = '.'.$file->getClientOriginalExtension();
// Save images for gallery
$regImage = $file->storeAs('/'. $post->id, $filename.$extension, 'post_images');
// Create a new image in db
Image::create([
'user_id' => auth()->user()->id,
'post_id' => $post->id,
'position' => $position,
'filename' => $filename,
'extension' => $extension,
'src' => 'post_images',
'mime_type' => $file->getMimeType(),
'file_size' => $file->getSize(),
]);
}
public function saveMedia($post) {
// Make sure user owns post
abort_unless($post->user_id == auth()->user()->id, 403);
// Set default position
$position = 1;
// Save each image
foreach ($this->images as $file) {
$this->saveImage($file, $post, $position);
// Increment position for next image
$position++;
}
}
}
For sorting items in Livewire I would use https://github.com/livewire/sortable.
Sortable is very easy to use.
For filepond if the original image should be used again later I would save that image as well with a relation to the edited version.

Laravel send image from vue to controller

I'm trying to save an image when updating an item but I'm having trouble sending the file to the controller in order to save it. This is how I'm sending it
submit(item) {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post('/courses/' + item.id, {
name: this.ruleForm.name,
summary: this.ruleForm.summary,
description: this.ruleForm.description,
price: this.ruleForm.price,
hours: this.ruleForm.hours,
min_grade: this.ruleForm.min_grade,
file: this.imagen,
matery: this.matery,
remover: this.remover,
strict: this.strict
}).then(
() => {
this.$message({
type: 'success',
message: 'Guardado correctamente.'
});
this.loading = false
},
(res) => {
this.$message.error(parseError(res)[0]);
this.loading = false;
})
} else {
return false;
}
});
},
If I {{imagen}} and {{imageUrl}} in the vue this is the result respectively, this is why I'm sending the imagen and not the url
[object File]
blob:http://dev.inae.com/9c77fa72-b778-45c9-8ab2-0a9084282415
When I Log::info($request) this is the output, when adding a file and changing text and saving,
local.INFO: array (
'name' => 'Principiante Clase 3 (automático)',
'summary' => 'Enseñaremos a compresionar el vehículo y la utilización de
cambios en vehículo automático',
'description' => '<p>Enseñaremos a compresionar el vehículo y la utilización de
cambios en vehículo automático (viaje a fraijanes).</p>',
'price' => 52000,
'hours' => 2,
'min_grade' => 70,
'file' =>
array (
'uid' => 1576507762527,
),
'matery' => NULL,
'remover' => false,
'strict' => false,
)
However if I only add the image and don't change anything else, nothing happens in the Log
Code for updating the image in the controller, in the update function
//Log is here
$editCourse = Course::find($id);
$destino = "img/courses";
$link = public_path();
if ($request->hasFile('file')) {
if (!empty($editCourse->image) && file_exists($link . $editCourse->image)) {
unlink($link . $editCourse->image);
}
$image = $request->file('file');
$imageName = Uuid::generate(4)->string . '.' . $image->getClientOriginalExtension();
$editCourse->image = '/' . $destino . '/' . $imageName;
$request->file('file')->move($destino, $imageName);
}
What could I be doing wrong?
You likely need to use the FormData object like so:
let data = new FormData();
data.append('file', this.imagen);
// Attach the other properties.
data.append(...);
$inertia.post(data);
This is because you shouldnt upload files using x-www-form-urlencoded, instead you should be using multipart/form-data which allows you to upload binary data. This also means that the backend will not receive a JSON string anymore, but a form-data response. Laravel should handle this automatically though.

Showing undefined variable while updating image in laravel

I am totally new in laravel and i have a small error in my code. Whenever I am updating the image it is showing the error
Undefined variable: company_image
Here is my code in Controller :
if(isset($request->company_image) && $request->company_image->getClientOriginalName()) {
$ext = $request->company_image->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->company_image->storeAs('public/company-logo',$file);
}
else
{
if(!$company_image){
$file='';
}
else
{
$file = $company_image;
}
}
Here is my code in resource :
<div class="form-group">
<div class="row">
<div class="col-md-3">
<label>Company Image</label>
</div>
<div class="col-md-9">
<input type="file" name="company_image" id="imageUpload" class="hide">
<label for="imageUpload" class="upload-poster mr-5">Select file</label> Max Size 2 MB<br>
#if($company_image)
<img src="{{ asset('storage/company-logo/'.$company_image)}}" class="organisation-logo">
#else
<img src="{{ asset('assets/admin/images/dummy-logo.jpg')}}" id="imagePreview" class="organisation-logo" alt="Your image will appear here.">
#endif
</div>
</div>
</div>
Please help me out, Thanks in advance.
Here is my code from where I am updating the data and the image. Please check this
public function update(Request $request, $jobId)
{
try
{
if(isset($request->company_image) && $request->company_image->getClientOriginalName()){
$ext = $request->company_image->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->company_image->storeAs('public/company-logo',$file);
}
else
{
if(!$company_image){
$file='';
}
else{
$file = $company_image;
}
}
$data = [
'job_title' => $request->input('job_title'),
'job_description' => $request->input('job_description'),
'publish_date' => Carbon::parse($request->input('publish_date'))->format('Y-m-d'),
'closing_date' => Carbon::parse($request->input('closing_date'))->format('Y-m-d'),
'company_image' => $file,
'organisation_type' => $request->input('organisation_type'),
'organisation' => $request->input('organisation'),
'country' => $request->input('country'),
'state' => $request->input('state'),
'city' => $request->input('city'),
'posted_by' => $userId
];
$rs = null;
if($request->input('temp_job') == 1){
$rs = Job::updateOrCreate(['temp_job_id'=> $jobId], $data);
}
else{
$rs = Job::where(['id'=> $jobId])->update($data);
}
if($rs){
$message = array('flag'=>'alert-success', 'message'=>'Job Updated Successfully');
return redirect()->route('auth.job.index')->with(['message'=>$message]);
}
$message = array('flag'=>'alert-danger', 'message'=>'Unable to update new job, Please try again');
return redirect()->route('auth.job.index')->with(['message'=>$message]);
}
catch (Exception $e)
{
$message = array('flag'=>'alert-danger', 'message'=>$e->getMessage());
return back()->with(['message'=>$message]);
}
}
Make sure , you are passing company_image variable in view.
if(!$company_image){
$file='';
}else{
$file = $company_image;
}
problem is here, you need to make sure $company_image is declared, before you can use it in if statement inside controller.
Example:
//declare company_image
$company_image = ''; //or $company_image = null;
//here logic to change $company_image if needed
//check if not empty/false
if(!$company_image){
$file='';
}else{
$file = $company_image;
}
Also you can check if variable exist with isset():
if(isset($company_image) && !$company_image){
$file='';
}else{
$file = $company_image;
}
Also make sure you pass this varaible in view. view('myView', compact('company_image'))
Updated Answer:
//Declare file as empty
$filePath = '';
//check if file uploaded and is valid
if($request->hasFile('company_image') && $request->file('company_image')->isValid()){
//get file extension
$ext = $request->company_image->extension();
//Generate File name
$file = date('YmdHis').rand(1,99999).'.'.$ext;
//Save file, storeAs() will return stored file path
$filePath = $request->company_image->storeAs('public/company-logo',$file);
}
Use $filePath to update the path in DB
$data = [
...
'company_image' => $filePath,
...
];
In view you can simply use {{ asset($company_image) }} check Laravel docs
Complete update function
public function update(Request $request, $jobId) {
try{
//Declare file as empty
$filePath = '';
//check if file uploaded and is valid
if($request->hasFile('company_image') && $request->file('company_image')->isValid()){
//get file extension
$ext = $request->company_image->extension();
//Generate File name
$file = date('YmdHis').rand(1,99999).'.'.$ext;
//Save file, storeAs() will return stored file path
$filePath = $request->company_image->storeAs('public/company-logo', $file);
}
$data = [
'job_title' => $request->input('job_title'),
'job_description' => $request->input('job_description'),
'publish_date' => Carbon::parse($request->input('publish_date'))->format('Y-m-d'),
'closing_date' => Carbon::parse($request->input('closing_date'))->format('Y-m-d'),
'company_image' => $filePath,
'organisation_type' => $request->input('organisation_type'),
'organisation' => $request->input('organisation'),
'country' => $request->input('country'),
'state' => $request->input('state'),
'city' => $request->input('city'),
'posted_by' => $userId
];
$rs = null;
if($request->input('temp_job') == 1){
$rs = Job::updateOrCreate([
'temp_job_id'=> $jobId
], $data);
} else{
$rs = Job::where([
'id' => $jobId
])->update($data);
}
if($rs){
return redirect()->route('auth.job.index')->with([
'message' => [
'flag' => 'alert-success',
'message' => 'Job Updated Successfully'
]
]);
}
return redirect()->route('auth.job.index')->with([
'message'=> [
'flag' => 'alert-danger',
'message' => 'Unable to update new job, Please try again'
]
]);
}catch (Exception $e){
return back()->with([
'message'=> [
'flag' => 'alert-danger',
'message' => $e->getMessage()
]
]);
}
}

Magento custom image upload doesn't work

I need to create an image upload field for posts in Magento Blog Module (AW blog).
Therefore, each post needs to contain an image.
I edited the following files:
/home/clients/websites/w_gale/public_html/gale/app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php
added fieldset like this:
$fieldset->addField('fileinputname', 'image', array(
'label' => Mage::helper('blog')->__('Upload image'),
'required' => false,
'name' => 'fileinputname',
'required' => true,
'style' => 'height:100px;border:2px solid #999;',
));
on top of this file, in the right place, I defined form like this:
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
)
);
In Blogcontroller.php I added the following code, just bellow the if ($data = $this->getRequest()->getPost()) { line
if(isset($_FILES['fileinputname']['name']) && (file_exists($_FILES['fileinputname']['tmp_name']))) {
try {
$uploader = new Varien_File_Uploader('fileinputname');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS ;
$uploader->save($path, $_FILES['fileinputname']['name']);
$data['imageurl'] = $_FILES['fileinputname']['name'];
} catch(Exception $e) {
}
} else {
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1)
$data['imageurl'] = '';
else
unset($data['fileinputname']);
}
However, the upload doesn't work. What am I doing wrong?
I added a special row in appropriate field in a database.
The frontend section displays the database value when I enter it manually.
Thanks
This code of method from data helper which uploads image. You need implement method getBaseDir() (which returns dir where you wish store your uploaded files) by yourself.
/**
* Upload image and return uploaded image file name or false
*
* #throws Mage_Core_Exception
* #param string $scope the request key for file
* #return bool|string
*/
public function uploadImage($scope)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addValidator('ImageSize', true, $this->_imageSize);
$adapter->addValidator('Size', true, $this->_maxFileSize);
if ($adapter->isUploaded($scope)) {
// validate image
if (!$adapter->isValid($scope)) {
Mage::throwException(Mage::helper('mycompany_mymodule')->__('Uploaded image is not valid'));
}
$upload = new Varien_File_Uploader($scope);
$upload->setAllowCreateFolders(true);
$upload->setAllowedExtensions(array('jpg', 'gif', 'png'));
$upload->setAllowRenameFiles(true);
$upload->setFilesDispersion(false);
if ($upload->save($this->getBaseDir())) {
return $upload->getUploadedFileName();
}
}
return false;
}
You're using the right code. I solved the problem by using the right MYSQL data type. When I changed the data type from 'text' to 'varchar(255)' it solved the problem
And ... make sure that you add the following code:
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
)
);
in /app/code/community/AW/Blog/Block/Manage/Blog/Edit/Form.php
NOT: app/code/community/AW/Blog/Block/Manage/Blog/Edit/Tab/Form.php

Resources