I'm trying to upload an image with ajax like this:
ROUTE
Route::get('upload', 'PostController#addPhoto');
VIEW
<form action="" id="upload" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="hidden" name="_token" value="{{csrf_token()}}" id="token">
Upload
</form>
CONTROLLER
public function addPhoto(Request $request){
$file = $request->file('file');
//dd($file);
return response()->json(['file'=>$file]);
}
JS
function upload(){
var token = $('#token').val();
var route = "http://localhost:8000/upload";
var form = $('#upload')[0];
var formData = new FormData(form);
console.log(form);
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: "GET",
cache: false,
dataType:'json',
processData: false,
contentType: false,
data: {'file': formData},
success:function(data){
console.log(data);
},
});
}
var uploaded = document.querySelector('#submit').onclick= upload;
In my controller dd($file); return null. Please how can i fix this error? how can i get the file image well? Maybe some error in ajax or form? I would like upload file image, thank you for your help!
Related
There is an input(text) in my page so users can insert the name of the file and upload the file itself, then press on Upload button.
I want to send the selected file and its name from input(text) to my controller in one ajax request.
How does it work ?
Here is the HTML Code:
<!--This is my upload section-->
<div class="custom-file col-md-4">
<input type="file" class="custom-file-input" id="theFile" required="">
<label class="custom-file-label" for="theFile"></label>
</div>
<!--This is my input section-->
<div class="col-sm-3">
<div class="form-group">
<label for="fileName">Enter the file name: </label>
<input type="text" class="form-control" id="fileName" placeholder="">
</div>
</div>
Here is what I tried for Ajax Code which doesn't work:
var formData = new FormData();
formData.append('upload', $('#questionFile')[0].files[0]);
$.ajax({
url:'the url of my controller is here',
type: 'POST',
data: {
'file' : formData,
'fileName' : $("#fileName").val()
},
cache: false,
processData: false,
contentType: false
})
Here is my method in my controller:
[HttpPost("getFile")]
[AllowAnonymous]
public IActionResult getFile(IFormFile file,string fileName)
{
//This is a method in my service project which uploads file
SaveQuestionFile(file, fileName);
return Ok("Uploaded");
}
You need to add a file which name is file,and add a FileName which name is fileName to formData,so that you can get the file and filename in action:
var formData = new FormData();
formData.append('file', $('#theFile').get(0).files[0]);
formData.append('fileName', $("#fileName").val());
$.ajax({
type: "POST",
url: "the url of my controller is here",
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});
result:
In Jquery pass the file using FormData
var fileData = new FormData();
var fileUpload = $("#fileId").get(0).files;
fileData.append("FILE", fileUpload[0]);
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: "url here",
data: fileData,
success: function (result) {
},
error: function (data) {
},
complete: function () {
}
});
In C# get file from request and data which is appended
public IActionResult getFile()
{
List<IFormFile> files = (List<IFormFile>)Request.Form.Files;
//if multiple
foreach (IFormFile file in files)
{
string fileName = file.FileName;
}
}
Im trying to send file to api using ajax , but form-data always null in both cases mentioned below
<form id="myformdoc">
<input type="file" size="45" name="file" id="file">
</form>
<script>
$('#file').on("change", function () {
// var formdata = new FormData($('form').get(0));
let myForm = document.getElementById('myformdoc');
let formData = new FormData(myForm);
$.ajax({
url: url,
type: 'POST',
data: formdata ,
cache: false,
processData: false,
contentType: false,
success: function (color) {
;
},
error: function () {
alert('Error occured');
}
});
});
</script>
Any idea why form-data always null ?
Try adding multipart/form-data in contentType parameter.
You need to use
formData append to add files to your formData function.
Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.
If you have other inputs in your form you can append them as well if you like to.
formData.append('file', $(this)[0].files[0])
Demo:
$('#file').on("change", function() {
//Initialize formData
let formData = new FormData();
console.log($(this)[0].files)
formData.append('file', $(this)[0].files[0]) //append files to file formData
$.ajax({
url: 'url',
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(color) {
console.log(color);
},
error: function() {
alert('Error occured');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" size="45" name="file" id="file">
</form>
I am trying to upload mp3 file to server without using submit button i am using ajax but file not uploading to server.Where i am wrong here is my code
<script>
$(document).ready(function() {
$('#fileToUpload').change(function(){
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "modules/phone/newvoicemail.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
}
});
});
});
</script>
In newvoicemail.php i put following code
$src = $_FILES['file']['tmp_name'];
$file_name = $_FILES['fileToUpload']['name'];
$file_size =$_FILES['fileToUpload']['size'];
$file_tmp =$_FILES['fileToUpload']['tmp_name'];
$file_type=$_FILES['fileToUpload']['type'];
move_uploaded_file($file_tmp,"voicemail/".$file_name);
here is my html code
<form name="voicemailform" action="modules/phone/voicemail.php" method="POST" enctype="multipart/form-data" class="form-inline for-frm">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
Since you are uploading using ajax, you do not need name,action,
method and enctype attributes on your HTML form tag. Same applies to name attribute of file input tag.
You need to add enctype: 'multipart/form-data', to $.ajax({...});
Since you are appending form data with param name file in JS as
form_data.append('file', file_data);, you should access it in php
as $_FILES['file'] and not $_FILES['fileToUpload']
HTML Code:
<form class="form-inline for-frm">
<input type="file" id="fileToUpload">
</form>
JS Code:
$('#fileToUpload').change(function () {
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "modules/phone/newvoicemail.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
console.log(data);
}
});
});
PHP Code: newvoicemail.php
<?php
$src = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
move_uploaded_file($src, "./voicemail/".$file_name);
i want upload image but its show below error how to solve this problem, because other format of html working fine ..i want use in angularjs
500 (Internal Server Error)
<input type="file" name="file" id="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
$scope.uploadFile = function(files) {
var fd = new FormData();
fd.append("file", files[0]);
$http.post(http://www.example.com/id/123, fd, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).success(res => {
var data = res.headers.get('application/json');
console.log(data);
}).error(function(err) {
console.log('sss');
});
};
but when i check use below format its working fine but i want response because i need save into database
<form action="http://www.example.com/id/123" method="post" enctype="multipart/form-data">
Upload: <input type="file" name="upload_image"><br/>
<input type="submit" value="submit">
</form>
its working for me.
<form id="data" method="post" enctype="multipart/form-data">
<input type="file" id="file" ng-model="files" name="upload_image">
<input type="submit" value="submit">
</form>
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:url,
type: 'POST',
data: formData,
async: false,
success: function (response) {
$scope.showimage= response.image_path;
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);