I want to upload multiple files in laravel with metadata. Like file custom name and file category.
I tried to add some property in frontend using js but I can see them in the controller
here the code
$(document).on('change','#file',function(e){
let file = e.target.files[0]
file.totalWords = 1234;
file.caytegory = 'category';
filesList.push(file)
});
let mainFormData = new FormData();
filesList.forEach(file => {
mainFormData.append('files[]',file)
})
$.ajax({
data: mainFormData,
url: 'controller_url',
type: "POST",
processData: false,
contentType: false,
headers: {
Accept : "application/json"
},
success: function (data) {
console.log(data)
});
},
error: function(response) {
console.log(response);
}
});
And here is my controller
return response()->json($request->file('files')[0]->caytegory);
What I want is just to access the category property from the submitted file but I cann't
Related
My web-application can only work with .xlsx-files. I created a function in my controller, which converts a .xls-file into an .xlsx-file. The conversion works totally fine. So whenever I try to open a .xls-file, I send it via Ajax request.
After that, I want to respond with the converted .xlsx-file, but it never arrives at the client.
Since the conversion works fine, i simplified the code, to just pass a simple .xlsx file, which didn't work aswell.
JavaScript:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
formData = new FormData();
formData.append("xlsfile", files[0]);
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: formData,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
Controller:
public IActionResult ConvertToXlsx(IFormFile xlsfile) {
//For simplification without conversion
//var xlsconverter = new XLSConverter();
//FileStreamResult response = xlsconverter.XLSConvert(xlsfile);
var path = $"wwwroot/temp/";
var filepath = Path.Combine(path, "test.xlsx");
MemoryStream x = new MemoryStream();
using(FileStream fs = System.IO.File.OpenRead(filepath)) {
fs.CopyTo(x);
}
return File(x, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
In the browser-network tab I get Status: net::ERR_CONNECTION_RESET
Am I missing a setting somewhere, which causes I simply can't respond with files?
If you want to pass file to action,try to use the following code:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: files[0],
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
And if you want to return file with content type,you can try to use:
public IActionResult ConvertToXlsx(IFormFile xlsfile)
{
return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
I'm trying to insert data into MongoDB using Mongoose, i created a form and sending data using two ajax post to the node, but Mongoose insert two document for each ajax call, I want to send my data to data as a single document.
This my server:
app.post("/cp" , upload , function(req , res){
console.log('file uploaded succcessfully');
var title = JSON.stringify(req.body.titles);
var file = req.file;
const courses = new Courses({
// courseTitle:c_title,
// courseSubtitle:c_subtitle,
// courseAuthor : c_creator,
// coursePrice : c_price,
courseVideo :file ,
courseTitles :title ,
// courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
});
Mongoose insert a document with title and without file and a document with file and without title,
Ajax:
if(e.submitter.id == "submitpostCp"){
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
data.submit = "submitAll";
var fileup = new FormData($('#form')[0]);
$.when(
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
).then(function() {
$.ajax({
url:'/cp',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: fileup,
success: function(res){
// alert(res);
},
error: function(){
alert('Error: In sending the request!');
}
})
});
}
In this case you should use findOneAndUpdate method with options {upsert: true}: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
I have following html
<form id="submit-form">
<input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple>
<input type="submit">
</form>
I am uploading files using ajax using formdata. The thing is that I don't want to send all files in one go using ajax. Instead I want to send single file per ajax request.
To upload files I am using following jQuery code
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
$.ajax({
url: url,
type: 'post',
data: formData,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
})
You can just use forEach method of FormData:
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
formData.forEach(function(entry) {
if (entry instanceof File) {
var fileForm = new FormData()
fileForm.append('resume', entry)
$.ajax({
url: url,
type: 'post',
data: fileForm,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
}
})
})
What I'm trying to do is theoretically simple: I want upload an image using ASP.NET, jQuery and AJAX, without submitting a form (this part is important).
So I have this:
HTML
<input type="file" accept="image/*" id="imguploader">
jQuery
var file_data = $("#imguploader").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
$.ajax({
type: "POST",
url: '#Url.Action("InsertImage", "Product")',
data: { file: form_data },
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
Controller
public ActionResult InsertImage(HttpPostedFileBase file) {
//blabla and the code to insert in the database.
return Content("");
}
What else I have tried:
// instead of using FormData, I tried to direclty capture the file using these:
var file = $("#imguploader").file;
//and
var file = $("#imguploader")[0].files;
//Same result (null).
The problem is that the file variable is always null no matter what. What I'm doing wrong? Can anybody helps?
You can manually set the FormData keys and values yourself.
<input type="file" name="imguploader" id="imguploader" />
<button id="btnUpload">Upload</button>
Create FormData and set a new key/value
$("#btnUpload").on("click", function(e) {
e.preventDefault();
var file = $("#imguploader").get(0).files[0];
var formData = new FormData();
formData.set("file", file, file.name);
$.ajax({
url: '#Url.Action("InsertImage", "Product")',
method: "post",
data: formData,
cache: false,
contentType: false,
processData: false
})
.then(function(result) {
});
});
The controller
[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{
}
I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});