I want to upload multiple image files and send it via email to customers. But the ajax request get this error call to a member function getclientoriginalname() on array when uploadMultiple: true, added to dropzone. Multiple images uploaded without that option. Anyway i want to email that multiple files, how can i do this?
dropzone js code:
Dropzone.options.uploadimg = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, //MB
acceptedFiles: ".jpeg,.jpg,.png",
uploadMultiple: true,
addRemoveLinks: true,
success: function(file, response)
{
$.notify({
message: 'Image uploaded Successfully!'
},
{
type: 'success'
});
},
error: function(file, response)
{
return false;
console.log('fail to upload');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}
SendMailController to send uploaded images.
public function sendNotifications(Request $request)
{
$id_int = Cookie::get('jobid');
$img_name = Cookie::get('imgName');
$data = DB::table('customers')
->join('jobs', 'jobs.id', '=', 'customers.id')
->select('firstname','email')
->where('jobs.id', '=', $id_int)
->get()->toArray();
foreach ($data as $value) {
$customer_firstname = $value->firstname;
$customer_email = $value->email;
}
$pathToFile = public_path() . "\\uploads\\" . $img_name;
//send the email to the relevant customer email
Mail::to($customer_email)->send(new SendMail($customer_firstname, $pathToFile), function($message){
$message->attach($pathToFile);
});
}
Image upload controller:
class ImageUploadController extends Controller
{
public function uploadImage(Request $request){
$img_file = $request->file('file');
$imgName = $img_file->getClientOriginalName();
Cookie::queue(cookie('imgName', $imgName, $minute = 5));
$img_file->move(public_path('uploads'), $imgName);
}
}
When i uploaded multiple images and sendinding via email, it only send the last uploaded file in dropzone. How can i send all uploaded files?
since its multiple files you need to loop through the file variable to get the files
class ImageUploadController extends Controller
{
public function uploadImage(Request $request){
$img_files = $request->file('file');
foreach($img_files as $img_file){
$imgName = $img_file->getClientOriginalName();
Cookie::queue(cookie('imgName', $imgName, $minute = 5));
$img_file->move(public_path('uploads'), $imgName);
}
}
}
Related
I have a block of code which would upload the file into the Google Drive. My main issue here is that when the user clicks on the upload button, the MD5 hash of the file will be checked and compared with the MD5 hashes of other files in the Google Drive and if there is a duplicate, then a message pop-up should be displayed stating that the file is a duplicated file and the user would need to reupload the file again.
This is from my GetGoogleDrive.cshtml file.
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<label for="file">Upload file:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" id="fileUpload" />
<script>
$('#fileUpload').click(function (e) {
if ($('#file').val() === "") {
Swal.fire({
title: 'Nothing',
text: 'No file selected',
type: 'error',
confirmButtonText: 'Again!!',
timer: 4000
})
}
else {
Swal.fire({
title: 'Wait awhile...',
text: 'File will be uploaded shortly',
type: 'success',
confirmButtonText: 'Okay, cool',
timer: 4000
})
}
});
</script>
The following code is for my upload file controller class.
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
GoogleDriveFilesRepository.FileUpload(file);
return RedirectToAction("GetGoogleDriveFiles");
}
This is the code for my Google Drive Files model class.
public static void FileUpload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
DriveService service = GetService();
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
HashGenerator(path);
compareHash(HashGenerator(path));
var FileMetaData = new Google.Apis.Drive.v3.Data.File();
FileMetaData.Name = Path.GetFileName(file.FileName);
FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
request.Fields = "id";
request.Upload();
}
}
}
Where should I generate the MD5 hash value of the file? In the C# or the JS?
i want to fetch the file based on my applications_id and i want to see it in the bootstrap file input and i want to delete it and replace with a new file. how can i do it. below is what i have tried .can anyone help me .i am stuck.
this is my contoller function SoleProprietorController.php
public function uploadImages(Request $request, $applications_id)
{
$applications = new Applications;
// $KRAPIN = Input::get('KRA_unique_field');
$applications_id = Input::get('applications_id_unique_field');
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
// request()->breg_cert->move(public_path('breg_cert'), $imgName);
// $imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$imgName = basename($request->breg_cert->move(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
return response()->json(['uploaded' => '/breg_cert/'.$imgName]);
}
}
this my web.php
Route::post('/uploadImages/{applications_id}', 'SoleProprietorController#uploadImages')->name('home');
this is my bootstrap file in my blade
<div class="col-md-4 mb-3">
<label for="validationServer023">Upload Business Registration Document</label>
<div class="form-group">
<div content="{{ csrf_token() }}" class="input-group input-file" name="Fichier1">
<input id="file-0a" name="breg_cert" value="" class="file" accept="text" type="file"> <br />
</div>
</div>
</div>
<script>
$("#file-0a").fileinput({
initialPreview: [
"<img src='/images/php' class='file-preview-image'>",
],
showUpload: true,
showRemove: true,
showCaption: true,
showPreview: true,
showClose: false,
autoOrientImage: true,
showUploadedThumbs: false,
uploadAsync: false,
uploadUrlThumb: false,
deleteUrl: "/public/KFS_Business_Registration_Certificates",
uploadUrl: "/uploadImages/{applications_id}",
// dataUrl: "/breg_cert/",
// uploadUrl: '/public/KFS_Business_Registration_Certificates', // you must set a valid URL here else you will get an error
theme: 'fa',
uploadExtraData: function() {
return {
_token: "{{ csrf_token() }}",
};
},
allowedFileExtensions: ['jpg', 'png', 'gif', 'pdf', 'jpeg'],
overwriteInitial: false,
maxFileSize: 500,
maxFilesNum: 10,
//allowedFileTypes: ['image', 'video', 'flash'],
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
</script>
1.Use code like this to store uploaded file and associate it with your Applications
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
$imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
}
https://laravel.com/docs/5.8/requests#storing-uploaded-files
To store an uploaded file, you will typically use one of your configured filesystems. The UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.
The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a file name, since a unique ID will automatically be generated to serve as the file name.
To handle delete/replace create a corresponding controller method and POST route and then provide the route to deleteUrl option.
In the above method check the filename associated and unlink it. (actual code depends on what dd($request); output)
To show stored image as preview add option to $("#file-0a").fileinput({
initialPreview: [
"<img src='/images/path-to.jpg' class='file-preview-image'>",
],
I try to change value of my column in users table with x-editable and I get 419 error on network.
codes
here is my CONTROLLER
public function changeprimaryaddress(Request $request){
try {
$id = $request->input('pk');
$field = $request->input('name');
$value = $request->input('value');
$user = User::findOrFail($id);
$user->{$field} = $value;
$user->save();
} catch (Exception $e) {
return response($e->getMessage(), 400);
}
my ROUTE
Route::post('/changeprimaryaddress','UserController#changeprimaryaddress')->name('changeprimaryaddress');
my HTML code
<a href="#"
class="change"
data-type="select"
data-name="address_id"
data-pk="{{ $user->id }}"
data-value="{{ $user->address_id }}"
data-title="Select New Primary Address"
data-url="{{ route('changeprimaryaddress') }}">Change</a>
my JAVASCRIPT
<script type="text/javascript">
$(function() {
$('.change').editable({
source: [
#foreach($addresses as $address)
{ value: '{{ $address->id }}', text: '{{ $address->address }} - {{$address->city->name}}, {{$address->state->name}}, {{$address->country->name}}, {{$address->postalcode}}' }
#unless ($loop->last)
,
#endunless
#endforeach
]
});
});
</script>
screenvideo
If you like to see the process and errors i provided small video you can see.
result
any idea why is that?
thanks to #SagarGautam. I added
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
its working now.
It is because you are not sending csrf token to the controller. either send the token, or do the following to exclude it.
open your app/Http/Middleware/VerifyCsrfToken.php file, and put the below code:
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'changeprimaryaddress',
];
}
I'm usin react.js(ver 15) and i want to upload the files with yii2 api.
My code is as follows:
My component(in react):
import React, { Component } from 'react';
import Header from './Heaader';
/* global $ */
class New extends Component {
constructor(props){
super(props);
this.state = {
cates: [],
subcats: [],
radioSelected: "f"
};
}
submitted = (e) => {
e.preventDefault();
var file_data = $('#filee')[0].files;
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "http://blog.dev/ads",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
},
error: function(){}
});
};
render(){
return (
<div>
<Header isNew="true" />
<div style={{marginTop: 2 + 'em'}}>
<form onSubmit={this.submitted}>
<input type="file" id="filee" />
<button type="submit">Sub</button>
</form>
</div>
</div>
);
}
Server Side:
In my controller:
<?php
namespace frontend\controllers;
use Yii;
use yii\rest\ActiveController;
class AdsController extends ActiveController
{
public $modelClass = 'frontend\models\Ads';
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
public function actions()
{
$actions = parent::actions();
unset($actions['create']);
return $actions;
}
public function actionCreate()
{
print_r($_FILES);
}
}
My problem is that $_FILES array is empty!
When I send data other than the file, $_POST works without problems(While this is the case in ajax request: processData:true and contentType:true ).
but $_FILES is empty.
Please guide me and tell me where the problem is?
Make sure your form has the correct encoding i.e <form enctype=multipart/form-data> for file uploads. this is most likely the reason why your $_FILES is empty
Yii 2 specifies a uniform API for fetching/saving uploads by using UploadedFile::getInstance($model, 'imageFile'); from the yii\web\UploadedFile; You should use it to access the uploads.
All the Best
I can save all data varchar/text element from my form, but I can't save my path image.
Whats is wrong with my code?
Lets see my create.blade.php I can save value of var deadline but I can't save value of var path:
Form::open(array('url' => 'imagesLoker', 'files' => true))
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
{!!Form::label('Deadline Lowongan : ')!!}
{!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
</div>
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('path') !!}
</div>
</div><!-- /.box-body -->
</form>
{!!Form::close()!!}
This is my Controller:
public function store(Request $request)
{
Lowongan::create($request->all());
return "data all";
}
This is my Ajax to create the data:
$("#createLoker").click(function(){
var datas = $('form').serializeArray();
var route = "http://localhost:8000/lowongan";
var token = $("#token").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post(route,{
deadline: $("#deadline").val(),
path: $("#path").val()
}).done(function(result){
console.log(result);
});
});
I don't know this is important or no to setting parse data in my Modal, but I just put this code in my Modal:
class Lowongan extends Model
{
protected $table = 'Lowongan';
protected $fillable = ['path','deadline'];
public function setPathAttribute($path){
$this->attributes['path'] = Carbon::now()->second.$path->getClientOriginalName();
$name = Carbon::now()->second.$path->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($path));
}
}
And the last I set the directory to save the image. This is setting in the config/filesystem:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imagesLoker'),
],
I can save the data deadline but no for image :( .. If there is any idea for how to save the image path, I will be pleased to know it.
In your form you have to allow file upload option in laravel like.
Form::open(array('url' => 'foo/bar', 'files' => true))
check the file upload section of laravel doc
Hope it helps..
please follow these steps
in view
change {!!Form::file('path') !!} to {!!Form::file('file') !!}
In controller
please note i have set the upload path to root/public/uploads/ folder
public function store(Request $request)
{
$file = Input::file('file');
$path = '/uploads/';
$newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
// Move the uploaded file
$upSuccess = $file->move(public_path() . $path, $newFileName);
$result = file_exists(public_path() . $path . $newFileName);
$fileData =[
'fileType' => $file->getClientOriginalExtension(),
'filePath' => substr($path, 1) . $newFileName
];
Input::merge(array('path' => $fileData["filePath"]));
Lowongan::create($request->all());
return "data all";
}