I can upload my file using to amazon s3 bucket successfully using my api and i can get a response:
But when i integrate this api into my application it says Call to a member function getClientOriginalName() on null i dont know where i am doing wrong:
My Api method:
public function uploadToAws(Request $request) {
$file = $request->file('image');
$imageName = 'company_logo/' . $file->getClientOriginalName();
Storage::disk('s3')->put($imageName, file_get_contents($file));
Storage::disk('s3')->setVisibility($imageName, 'public');
$url = Storage::disk('s3')->url($imageName);
$resultArray = ['status' => 1, 'message' => 'File uploaded to s3 bucket!', 'dataArray' => $url];
return Response::json($resultArray, 200);
}
and my response of this api:
{
"status": 1,
"message": "File uploaded to s3 bucket!",
"dataArray": "https://spikessales.s3.amazonaws.com/company_logo/template3.jpg"
}
I can perfectly upload file to s3 bucket using this api:
But when i integrate to my application view it says Call to a member function getClientOriginalName() on null i dont where i am wrong:
This view code using ajax call:
///upload logo sec
$(document).on('click', '.browse', function () {
var file = $(this).parent().parent().parent().find('.changefle');
file.trigger('click');
});
$(document).on('change', '.changefle', function () {
var imagename = "";
$.each($(".changefle")[0].files, function (i, file) {
imagename = file.name;
});
$.ajax({//Process the form using $.ajax()
type: 'post', //Method type
url: 'http://127.0.0.1:8000/api/upload_aws', //Your form processing file
URL
data: {
image: imagename
}, //Forms name
dataType: 'json',
success: function (data) {
console.log(data);
// localStorage.setItem("set-compylogo", companylogo);
},
error: function (data) {
console.log("error");
}
Your help will be highly appreciated!
It might be your ajax need more headers to upload file. or may be it need this:
$.ajax({
headers: {
'X-CSRF-TOKEN': your_crsf_token,
'Content-type: text/html;charset=ISO-8859-1'
},
...
});
For further information, you might want to check this out: AJAX File Upload with XMLHttpRequest
You are sending a string (image name) instead of a FILE object. To use those methods laravel needs a file object. So imagename = file; instead of imagename = file.name
Related
I have tried majority of other questions here and other solutions and nothing has worked so far.
What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.
Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,
second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.
Route:
Route::post('/upload', 'UploadController#uploadSubmit');
View:
<div>
<input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
<br />
<div id="files_list"></div>
<p id="loading"></p>
<input type="hidden" name="file_ids" id="file_ids" value="" />
</div>
Ajax call:
$(document).ready(function(){
$("input").change(function(){
alert('triggered');
debugger;
$('#fileupload').fileupload({
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
}
dataType: 'json',
add: function (e, data) {
$('#loading').text('Uploading...');
data.submit();
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
if ($('#file_ids').val() != '') {
$('#file_ids').val($('#file_ids').val() + ',');
}
$('#file_ids').val($('#file_ids').val() + file.fileID);
});
$('#loading').text('');
}
});
});
});
});
Controller:
public function uploadSubmit(Request $request){
$files = [];
dd(request());
foreach($learnerFiles as $key => $learnerFile){
if(count($learnerFile) > 0){
$path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
$search = 'public/' ;
$trimmed = str_replace($search, '', $path) ;
//dd($learnerFiles);
$file = FileUpload::create([
'user_id' => $learner->id,
'file_name' => $key,
'path' => $trimmed
]);
}
else{
}
$file_object = new \stdClass();
$file_object->name = $key;
$file_object->size = round(Storage::size($path) / 1024, 2);
$file_object->fileID = $learner->id;
$files[] = $file_object;
}
return response()->json(array('files' => $photos), 200);
}
I'm using the following method to upload images using Ajax call and Laravel back-end.
var uploader = $('#image-uploader[type="file"]');
var data = new FormData();
$.each(uploader.files, function() {
data.append('image[]', this);
});
data.append('_token', $('[name="csrf-token"]').attr('content'));
var url = '/upload'; //Or any target path with post method
$.ajax({
url: url,
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
alert('succeed');
}
});
Consider you can access to image files in server-side using $_POST['image] array.
Hope this helps you.
I'm working on a Laravel Spark project and I am trying to get a form to upload a folder to my S3 bucket. I have the form built:
<form enctype="multipart/form-data">
<input type="file" name="resume" v-model="form.resume">
<button #click="updateProfile">Update Profile</button>
</form>
Then I have a vue component set up to handle the form submit:
Vue.component('resume-links', {
template: '#edit-resume-links',
data() {
return {
form: new SparkForm({
resume: ''
})
};
},
methods: {
updateProfile() {
console.log(this.form.resume);
Spark.post('/route/to/controller', this.form).then(response => {
console.log(response);
});
}
}
});
Then in my laravel controller:
$resume = $request->file('resume');
$resumeFileName = time() . '.' . $resume->getClientOriginalExtension();
$s3 = \Storage::disk('s3');
$filePath = '/resumes/' . $resumeFileName;
$s3->put($filePath, file_get_contents($resume), 'public');
When I try to submit the form with a file it throws this error:
Call to a member function getClientOriginalExtension() on null
I have tried var_dumping $resume right after setting it to the file() and what I see outputted to the console is a bunch of js looking code
From everything that I reading it looks like file uploads with Laravel is super easy and I don't know why I am having this issue. Any assistance/advice would be appreciated! Thanks!
First of all, your file input needs to have the v-el attribute rather than v-model.
In your case it would be <input type="file" name="form" v-el:resume />.
Next, in your Vue component, you need to gather the FormData so that it becomes possible to send the file to the server. Files have to be handled slightly differently to plain text fields and such.
Add this to your methods object:
gatherFormData() {
const data = new FormData();
data.append('resume', this.$els.resume.files[0]);
return data;
}
In your updateProfile method you now need to send this data off to the server as a POST request.
updateProfile(e) {
e.preventDefault();
var self = this;
this.form.startProcessing();
$.ajax({
url: '/route/to/controller',
data: this.gatherFormData(),
cache: false,
contentType: false,
processData: false,
type: 'POST',
headers: {
'X-XSRF-TOKEN': Cookies.get('XSRF-TOKEN')
},
success: function (response) {
self.form.finishProcessing();
console.log(response)
},
error: function (error) {
self.form.setErrors(error.responseJSON);
}
});
},
Finally, in your controller method, you can now handle the file as normal
(e.g., $request->file('resume');)
Handling files with Laravel really is a breeze – you just need to make sure you're actually getting them to the server ;)
I want to delete files from server which have been uploaded through Dropzone.But,Only thumbnails have been deleted.File in the server not erased.I have got an error in console.http://localhost:8000/upload/delete 500 (Internal Server Error)'
My Upload Method In Controller
public function upload(Request $request){
$file= $request->file('file');
$filename=$file->getClientOriginalName();
$upload='uploads/topics';
$file->move($upload, $filename);
}
Dropzone Script file.
Dropzone.options.addImages = {
maxFilesize: 8,
addRemoveLinks: true,
dictRemoveFile: 'Remove',
init:function() {
this.on("removedfile", function(file) {
$.ajax({
type: 'POST',
url: 'upload/delete',
data: {id: file.name},
dataType: 'html',
success: function(data){
var rep = JSON.parse(data);
}
});
} );
},
}
My delete method in controller.
public function delete(Request $request){
$filename = $request->input('id');
unlink('uploads/topics'.$filename);
}
Two issues that I can see right away:
In your delete controller method you are trying to access $request but you haven't injected it.
The request input method is lowercase.
I believe this is closer to what you need:
public function delete(Request $request){
$filename = $request->input('id');
unlink('uploads/topics/' . $filename);
}
Some notes:
Whenever you get an "internal server error" that means you need to check your error logs. There are details in one of your log files that will tell you the exact error.
Right now your delete method could allow a user to delete things you may not want them to delete. I could easily post a filename to that endpoint and delete anything from your topics folder.
Even more dangerous, this code appears to be at risk for a traversal attack. See here for details: https://www.owasp.org/index.php/Path_Traversal
okay i've been trying this for like 2 hrs now and cant to make this work. dropzone cant upload any file. the server says "token not provided". im using laravel as backend and it uses jwt tokens for authentication and angular as front end. here's my dropzone config.
$scope.dropzoneConfig = {
options: { // passed into the Dropzone constructor
url: 'http://localhost:8000/api/attachments'
paramName: 'file'
},
eventHandlers: {
sending: function (file, xhr, formData) {
formData.append('token', TokenHandler.getToken());
console.log('sending');
},
success: function (file, response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
}
};
and the route definition
Route::group(array('prefix' => 'api', 'middleware' => 'jwt.auth'), function() {
Route::resource('attachments', 'AttachmentController', ['only' => 'store']);
}));
and the controller method
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$file = Input::file('file');
return 'okay'; // just until it works
}
the token is correct and is actually getting to the server (because i tried returning the token using Input::get('token') in another controller function and it works). can someone tell me what im doing wrong? im getting "400 Bad Request" with "token_not_provided" message...
thanks for any help. and i apologize for my bad english..
I'm not sure why appending the token to the form isn't working, but you could try sending it in the authorization header instead.
Replace
formData.append('token', TokenHandler.getToken());
With
xhr.setRequestHeader('Authorization', 'Bearer: ' + TokenHandler.getToken());
make sure you add the token to your call: Example you can add the toke as a parameter in your dropzone url parameter.
//If you are using satellizer you can you this
var token = $auth.getToken();// remember to inject $auth
$scope.dropzoneConfig = {
options: { // passed into the Dropzone constructor
url: 'http://localhost:8000/api/attachments?token=token'
paramName: 'file'
},
eventHandlers: {
sending: function (file, xhr, formData) {
formData.append('token', TokenHandler.getToken());
console.log('sending');
},
success: function (file, response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
}
};
Using mobile apllication here, I am sending image encoded data to php file using post method and getting the image url from the php file. The problem here is, I am not getting proper image while am sending string using ajax. When I place the image data manually, I am able to view the image, but when sending the image data using ajax call, unable to view the image.
<?php
//$image = $_POST['uploadedfile'];//not working if an ajax call is made what is the issue here
$image ="base64 string of an image here";//working if i place base 64 string here
$binary = base64_decode($image);
$fileName = time() . ".jpeg";
file_put_contents('images/' . $fileName, $binary);
if (file_exists('images/' . $fileName)) {
$myjson12 = "[";
$myjson12.='{';
$myjson12.='"Certificate":"http://domain/demo/images/'.$fileName.'"';
$myjson12.='}';
$myjson12.="]";
echo "$myjson12";
} else {
echo 'FAILURE';
}
?>
When I am accessing the file url and sending the parameter value the output is coming as url is too long: www.domain.com/getdata.php?uploadedfile=base64stringvalue;
here is my ajax call
$.ajax({
type: "POST",
url: "www.domain.com/getdata.php",
data: { "uploadedfile": c.toDataURL("image/jpeg") },
// dataType: "json",
success: function (response) {
console.log(response + "Sri");
$("#loadImg").hide();
alert("Success");
},
error: function (data) {
$("#loadImg").hide();
alert("Connection Failed");
}
});