When trying to upload a file CSV / Excel file and receiving it in an ajax request, it's not working as expected.
I used a formdata object to upload the files like such:
const formData = new FormData()
formData.append('file', file)
//upload the file to the server
Api.makeRequest('uploadFromFile', {
processData: false,
contentType: false,
enctype: 'multipart/form-data',
cache: false,
data: formData,
complete: function (xhr) {
if(xhr.status === 201 || xhr.status === 200){
console.log(xhr.responseJSON)
}else {
alert('error')
console.error(xhr.responseJSON)
}
}
})
As I read from the documentation, you have to extract it like such:
$file = $request ->file('file_key')
When using this syntax, I get an error, and Laravel can't extract the file:
public function uploadFromFile(Request $request){
if($request->hasFile('file')){
$file = $request->file('file');
return $file;
}else{
return response()->json(['error' => 'No file uploaded'], 400);
}
However, it works fine when I use the regular request->has() function. A return type is just an object. What am I doing wrong since I can't get the file in the correct format?
//This works, getting some data but not a proper file object
public function uploadFromFile(Request $request){
if($request->has('file')){
$file = $request->get('file');
return $file;
}else{
return response()->json(['error' => 'No file uploaded'], 400);
}
<script>
var droppedFiles='';
//input file change event to call this function
function FileUpload(e)
{
droppedFiles = e.target.files || e.dataTransfer.files;
}
$('#FrmId').on('submit', function (e) {
var $form = $('#FrmId');
var $input = $form.find('input[type="file"]');
var form_data = new FormData($('#FrmId')[0]);
if (droppedFiles)
{
$.each( droppedFiles, function(i, file) {
form_data.append( $input.attr('name'), file );
});
}
$.ajax({
type: "POST",
enctype: "multipart/form-data",
url: "url",
data: form_data,
contentType: false,
cache: false,
processData: false,
}).done(function (data) {
}).fail(function () {
});
return false;
});
</script>
Related
I want to send data using an Ajax request to PHP.
I have the following data in my formData variable:
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
Printing the form entries gives me this:
I do the request like this:
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
In post.php I print the recieved data:
print_r("First name: " . $_POST["fname"] . PHP_EOL);
print_r("Last name: " . $_POST["lname"] . PHP_EOL);
print_r("Email: " . $_POST["email"] . PHP_EOL);
print_r("Data: " . $_POST["data"] . PHP_EOL);
For some reason it does not receive the 'data' entry in the $_POST variable. I get the following notice: "Notice: Undefined index: data"
Why does that happen? Could I somehow send the blob information?
As requested, the whole code. (inputFname, inputLname and inputEmail are not null. The code is situated inside a button onclick event method.
let evtTgt = e.target;
const container = evtTgt.parentNode;
const audioElement = container.getElementsByTagName("audio")[0];
const audioURL = audioElement.src;
let newBlob = await fetch(audioURL).then(result => result.blob());
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
for (var key of formData.entries()) {
console.log(key[1]);
}
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
All this time I was looking for the blob contents inside the $_POST variable. I should have looked in the $_FILES variable instead!
I managed to get the file contents by calling this inside the php script:
$fileinfo = file_get_contents($_FILES['data']['tmp_name']);
I'm trying to send an image to an ajax handler via ajax. If I console.log the variable ìmage I am sending, it looks fine. As of now I am sending it to the handler and just trying to echo it back. But I get a blank response. I am sending the image: formData inside an object which I hope is ok.
Ajax:
var form_data = new FormData();
var image = $('#newImage').prop('files')[0];
var image_name = image.name;
var image_extension = image.name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension, ['gif', 'jpg', 'JPG', 'pjpeg', 'x-png', 'png', 'PNG', 'jpeg']) == -1) {
alert("Invalid Image File Type")
}
var image_size = image.size;
if(image_size > 700000) {
alert("Image too big!");
} else {
form_data.append('file', image);
}
let data = {
action: 'NewEventExhibition',
name: name,
description: description,
notes: notes,
status: status,
slug: slug,
start_date: start_date,
end_date: end_date,
event_code: '<?=$code?>',
image: form_data
};
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false,
mimeType: 'multipart/form-data',
success: function(response) {
alert(response);
},
fail: function(response) {
console.log(response);
}
})
}
});
Handler
if($_FILES['file']['name'] != '') {
$test = explode(".", $_FILES['file']['name']);
$extension = end($test);
$name = rand(100, 999).'.'.$extension;
$location = "/assets/images/".$name."";
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo $location;
}
```
That's not how you send a FormData object with ajax. The form_data object should be the thing that you send, not it being part of a bigger object.
I would recommend you to append all the fields of the object data to the form_data and send it.
Something like the following:
form_data.append('action', 'NewEventExhibition');
form_data.append('name', name);
form_data.append('description', description);
form_data.append('notes', notes);
form_data.append('status', status);
form_data.append('slug', slug);
form_data.append('start_date', start_date);
form_data.append('end_date', end_date);
form_data.append('event_code', '<?=$code?>');
instead of let data = { .... }.
Then you can send it with
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: 'multipart/form-data',
success: function(response) {
alert(response);
},
fail: function(response) {
console.log(response);
}
});
Please note the data: form_data.
I want to send FirstName, LastName and Image through Ajax Call to PHP. I am able to send the data without image, and I am able to send the image without text using formdata but the problem is I am not able to do both at a time. Kindly check my code what I am doing wrong:
<script>
function createBasicInfo() {
// For Image Send
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
// For Text Send
var data = {
'firstname' : jQuery('#firstname').val(),
'lastname' : jQuery('#lastname').val(),
};
**//Here Is the Problem, I am not able to append the data with Text**
formdata.append(data);
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
In above code if I comment
//formdata.append(data); // Then only image will send to php
And If I use in Ajax Call
data: data, // Then only FirstName & LastName will send to php without Image
I am not able to send text data and image both at the same time to php file.
Any idea or suggestion would be welcome.
You could just do this insted of formdata.append(data):
formdata.firstname = jQuery('#firstname').val();
formdata.lastname = jQuery('#lastname').val();
Just append your firstname and lastname into formdata. Then send full formdata.
<script>
function createBasicInfo() {
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
formdata.append('firstname', jQuery('#firstname').val());
formdata.append('lastname', jQuery('#lastname').val());
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
// ...
// ...
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp
i want to create a fileupload with ajax and jquery.i send formData to server.i can not get data and save image on server.
it is my code in javascript:
function UploadFile() {
var fileName = $('#uploadFile').val().replace(/.*(\/|\\)/, '');
if (fileName != "") {
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'p1.aspx/uploadPic',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (dt) {
alert(dt.d);
}
});
}
}
code in p1.aspx page:
[WebMethod]
public static string uploadPic(HttpPostedFile file)
{
return file.FileName;
}
it is not work and not return any thing!what is wrong?how can get image on server?
best reagrds.