Unprocessable Entity when trying to upload file via Ajax - php

I just moved my local code over to live server. Everything is working but when I try to upload an image on the live server I get "Unprocessable Entity" error. The file upload works perfectly on my local server. I am using Windows server with IIS and PHP 7.2 and my project is using laravel 5.5
I have already tried given full control permissions to IUSER and IIS_IUSRS. I also tried updating the php.ini file (file_uploads = On, upload_max_filesize = 20M,post_max_size = 20M)
My Form
<form class='form-inline' id='edit-property-image' enctype='multipart/form-data'>
<input type='hidden' id='property' value='$id' name='property'>
<input type='file' class='custom-file-input' id='propertyImage' name='propertyImage' onchange='propertyImageChange(this)'>
<a href='javascript:updatePropertyImage($id)' class='btn btn-primary'>Update Image</a>
</form>
Ajax Method
function updatePropertyImage(id)
{
$.ajax({
data:new FormData($("#edit-property-image")[0]),
async:false,
type:'post',
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST', // Type of response and matches what we said in the route
url: '/property/updateImage', // This is the url we gave in the route
success: function(response){ // What to do if we succeed
if(response.response == "success") {
$('.modal').modal('hide');
propertyDetails(id);
}
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
alert(errorThrown);
}
});
}
Controller
$id = $request->input('property');
$this->validate($request,[
'propertyImage' => 'image|max:1999|required'
]);
$response = "failed";
//Handle File Upload
if($request->hasFile('propertyImage')){
//Get Filename with extension
$fileNameWithExt = $request->file('propertyImage')->getClientOriginalName();
// Get just filename
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $request->file('propertyImage')->getClientOriginalExtension();
//Filename to store
$fileNameToStore = $id.'_'.time().'.'.$extension;
//Upload Image
$path = $request->file('propertyImage')->storeAs('public/property_images', $fileNameToStore);
$property = Property::find($id);
$property->image_url = $fileNameToStore;
$property->save();
$response = "success";
}
return response()->json([
'response' => $response,
]);

I fixed the issue. It was actually because my php.ini file did not specify a default temp folder. Once I added that the file upload worked.

Related

Summernote upload image not showing in the editor after submitting to update

I have been working on a project, using Summernote. My project is like a blog system and I need to upload contents and images.
I have checked the other posts here and other places and managed to insert images to the file with ajax where I want to save the images. However, when I am editing, an image is there but once I click "update button" (submit button in a form), the images won't be there anymore.
I also check the inspect and resource says
Request URL: http://localhost/cms/admin/includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG
This is the right path but after updating, I get a message like
Request URL: http://localhost/%22includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG/%22
Also status code says
Status Code: 403 Forbidden
Here is my code
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
for(let i=0; i < files.length; i++) {
$.upload(files[i]);
}
}
},
height: 300,
});
$.upload = function (file) {
let out = new FormData();
out.append('file', file, file.name);
$.ajax({
method: 'POST',
url: './includes/editor-upload.php',
contentType: false,
cache: false,
processData: false,
data: out,
success: function(url) {
$('#summernote').summernote("insertImage", url, 'filename');
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(textStatus + " " + errorThrown);
}
});
};
And this is my php code (editor-upload.php)
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'images/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'includes/images/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Insert uploaded image to summernote editor
Summernote image upload
Summernote 0.8.12 Image Upload And Delete
I have tried these but nothing worked for me.
I have of course Summernote js and css file and am using Summernote 0.8.18
I am sure I am doing something wrong but I can't figure this out yet.
I am hoping somebody can help me out.
If the images folder is inside of the includes folder, change the following line:
$destination = 'images/' . $filename;
to
$destination = './includes/images/' . $filename;
Next, enter the full URL name and the full path to the image instead of
echo 'includes/images/' . $filename;
Also, the editor-upload.php file in your Ajax upload script may be causing the 403 errors. if the upload file is not in the same folder as your form and index.php page, it can prove problematic.
Try moving the file to the same folder as your form with the summer note editor, and enter the file in your Ajax script as
'editor-upload.php'

Failed to load resource: the server responded with a status of 403 when using ajax to send post request on production server laravel

I am using ajax to send a request to a laravel controller with multiple images and other,
Everything work on local environement but when I upload to the production environement, the upload fails with the error
Failed to load resource:/property/images/add:1 the server responded with a status of 403 ()
Here is the ajax code
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()}
});
$('#images').change(function () {
event.preventDefault();
let image_upload = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
let images = $('#images')[0];
let p_id = $('input[name=p_id]').val();
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images[]', images.files[i]);
}
image_upload.append('TotalImages', TotalImages);
image_upload.append('p_id', p_id);
$.ajax({
method: 'POST',
url: '{{ route('image.add') }}',
data: image_upload,
contentType: false,
processData: false,
success: function (images) {
Swal.fire(
'Success!',
'Images uploaded successfully',
'success'
);
$('#images').reset();
},
error: function () {
Swal.fire(
'Failed!',
'An error occured please try again',
'error'
);
$('#images').reset();
}
});
});
and this is the controller code
public function store(Request $request)
{
//check if an image has been selected
if ($request->images) {
$total=$request->TotalImages;
$images = $request->images;
foreach($images as $image) {
$photo = new Photo;
$photo->p_id = $request->p_id;
$image_temp = $image;
//echo $image_temp; die;
if ($image_temp->isValid()) {
$extension = $image_temp->getClientOriginalExtension();
$filename = 'bks'.mt_rand(000, 9999999999) . '.' . $extension;
$filepath = 'uploads/property/large/' . $filename;
$webimagefilepath = 'uploads/property/small/' . $filename;
//upload the image
Image::make($image_temp)->resize(600, 600)->save($filepath);
Image::make($image_temp)->resize(200, 200)->save($webimagefilepath);
$photo->path = $filename;
$photo->alt_text = "Book sasa property image";
$photo->save();
}
}
}
return response()->json("Success");
}
I am using named routes and the name is the one used in the ajax url.
What could I be doing wrong and how can I solve it?

Call to a member function getClientOriginalName() on null

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

move_uploaded_file is not working in MAMP

I'm running into an issue using move_uploaded_file, specifically that it... doesn't work.
I have an input to upload the pdf:
<div>
Upload Resources
<input type="text" id="doc-name" name="doc-name">
<input type="file" id="doc-upload" name="doc-upload" accept="application/pdf">
<button id="upload-button">Upload</button>
</div>
And some jquery that sends a POST request with that file:
$("#upload-button").click(function() {
if ($('#doc-name').val() == '') {
var formData = new FormData();
var filename = $('#doc-name').val();
var uploaded = $('#doc-upload').val().split('\\');
var path = uploaded[uploaded.length - 1];
var file = $('#doc-upload').prop('files')[0];
formData.append("functionCall", "document-upload");
formData.append("filename", filename);
formData.append("path", path);
formData.append("file", file);
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(e) {
console.log(e);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorMessage);
}
});
)};
This sends to my functions file, which is set up kind of odd (it might actually be standard practice, I've just never seen it like this) in that it's one big switch statement; which case gets run is dependent on the functionCall variable passed in. So here is the function code for that specific case statement:
.
.
.
case "doc-upload":
$filename = $_POST['filename'];
$path = $_POST['path'];
$file = $_FILES['file'];
$uploadQuery = "INSERT INTO uploads (filename, path) VALUES ('$filename', '$path')";
$upload = mysql_query($uploadQuery);
if (move_uploaded_file($_FILES['file']['tmp_name'], 'test/' . $_FILES['files']['name'])) {
echo 'yay';
} else {
echo 'such is life';
}
Everything above the move_uploaded_file line works great, but I keep getting the 'such is life' line returned, and the transferred file does not show up in 'test/'. I know both the test folder and uploaded file are present thanks to a file_exists check. Any ideas about what I might have done wrong?

No size limitation while uploading the file to server in php

Here i am doing upload the any file(there is no file size restriction and user can upload the any file extension) to server through my php code (in codigniter) but when I am trying to upload the file which is size 185MB so it is giving me error. I also add the php.ini to my folder structure on server which is got from my server support. I did increased the upload size and also increases another related attribute. I can upload the file which is size 20MB but did not able to upload the file size 50mb, 100mb, etc. upload maximum file size working on localhost but not working on server. Please below is the my code. Please help me any changes in my code
upload the files through ajax
$.ajax({
url: '<?php echo base_url();?>files>',
type: 'POST',
dataType :'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
beforeSend:function() {
$("#progressbar").show();
$("#cmdSub").attr("disabled",true);
$("#cmdSub").val("Please Wait");
},
success: function (data) {
if(data.success != ""){
location.href = "<?php echo base_url();?>files/";
}
if(data.error != ""){
$("#f_name").val("");
$("#fnameinfo").html(data.error);
$("#cmdSub").attr("disabled",false);
$("#cmdSub").val("Submit");
}
},
error: function(xhr, textStatus, thrownError) {
alert("Error while uploading");
$("#cmdSub").attr("disabled",false);
$("#cmdSub").val("Submit");
$("#ffileinfo").html("");
},
data: formdata,
// this is the important stuf need to overide the usual post behavior
cache: false,
contentType: false,
processData: false
});
controller code
function uploadFile() {
$f_name = $_FILES['f_name']['name'];
$f_type = $_FILES['f_name']['type'];
$f_size = $_FILES['f_name']['size'];
$f_ext = pathinfo($_FILES['f_name']['name'], PATHINFO_EXTENSION);
$filename = pathinfo($_FILES['f_name']['name'], PATHINFO_FILENAME );
$filename = str_replace($arr_chars,"_",$filename);
$configFile = array (
'allowed_types' => '*',
'upload_path' => $file_upload_path,
'file_name' => $filename.'_'.$fid
);
$this->upload->initialize($configFile);
if($this->upload->do_upload('f_name')) {
//insert the record
} else {
$error = $this->upload->display_errors();
}
}
File upload size is probably a server config issue :)
Try this in your php.ini:
upload_max_filesize = 10M
post_max_size = 10M
--Edit (Thanks Big Chris)
The script could time out handling this request. So you should add this to your function
ini_set('max_execution_time', 120);
This tells php that this file can take up to 2 minutes to run
Hope that helps :)

Categories