Sending a File (PDF) through ajax to a JSP Servlet - javascript

I am trying to send two PDF Files )initially just one) through an HTML form using javascript (jquery or not), I have to receive both files in a controller of a JSP page (using Spring) and do something with both files.
Right now I have been trying some of the answers already posted here in SO, but I am not being able to get it to work correctly.
My HTML File
<form id="searchForm">
<table class=rightAlignColumns>
<tr>
<td><label for="File1"><spring:message code='File1' />:</label></td>
<td><input id="File1" type="file" name="File1" /> </td>
<td><label for="file2"><spring:message code='File2' />:</label></td>
<td><input id="file2" type="file" name="file2" /> </td>
</tr>
</table>
<br/>
<input type="submit" value="<spring:message code='Btn' />" />
</form>
My javascript
var fd = new FormData();
alert(document.getElementById('File1').files.length);
fd.append( 'File1', document.getElementById('File1').files[0] );
// fd.append( 'File2', document.getElementById('File2').files[0]);
$.ajax({
url:'myurl.json',
data: fd,
cache:false,
processData:false,
contentType:false,
type: 'POST',
success: function(data){
// alert(data);
}
});
On the controller I am doing what this other post said.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}
The problem I think it is in the javascript, because when the code enters to the Controller the list "items" has a size of 0, and going into the exception.
The expected result would be the user loading a PDF file into the Form, hitting submit and ajax sending the file to the server (controller), doing stuff correctly and sending back a result.
Right now the client is not uploading correctly the file.
As a side note, the file I am uploading is going to be used by pdfbox or google ocr in the controller.
Thanks in advance!

It worked using the next code:
JS:
function doAjax() {
// Get form
var form = $('#id_form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "controller/myMethod",
data: data,
processData: false, //prevent jQuery from automatically transforming the data into a query string
contentType: false,
cache: false,
dataType:'json',
success: function (e) {
$("#result").text(data);
alert("Success");
},
error: function (e) {
$("#result").text(e.responseText);
alert("Error");
},
complete: function () {
// Handle the complete event
alert("Complete");
}
});
}
And on the controller
#RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public String uploadFileMulti(#RequestParam("file") MultipartFile file,HttpServletRequest request) {
try {
//storageService.store(file, request);
System.out.println(file.getOriginalFilename());
return "You successfully uploaded " + file.getOriginalFilename();
} catch (Exception e) {
return "FAIL!";
}
}
My HTML file
<form class="form-horizontal" method="POST" enctype="multipart/form-data" id="id_form">
<label for="file">File:</label>
<input id="file" type="file" name="file" />
</form>

Related

Submit a Form using AJAX in ASP.Net Core MVC

I am working with ASP.Net Core 2.1, and trying to upload a file while returning it's url, without refreshing the page.
I am trying to write the JavaScript in site.js as the _RenderPartial("scripts") renders all scripts at the end of the page and hence directly using script tag in the razor view is not working. Secondly, adding it to site.js gives me an opportunity to call the script across the site views.
My Controller action looks like :
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> Upload()
{
// Read & copy to stream the content of MultiPart-Form
// Return the URL of the uploaded file
return Content(FileName);
}
My view looks like :
<form id="FileUploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
The site.js currently looks like :
function SubmitForm(form, caller) {
caller.preventDefault();
$.ajax(
{
type: form.method,
url: form.action,
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
})}
Presently, the code bypasses the entire script and the file is uploaded and new view displaying the file name is returned. I need help to create the javascript.
Unfortunately the jQuery serialize() method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).
What you may do is, create a FormData object, append the file(s) to that. When making the
ajax call, you need to specify processData and contentType property values to false
<form id="FileUploadForm" asp-action="Upload" asp-controller="Home"
method="post" enctype="multipart/form-data">
<input id="uploadfile" type="file" />
<button name="uploadbtn" type="submit">Upload</button>
</form>
and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.
$(function () {
$("#FileUploadForm").submit(function (e) {
e.preventDefault();
console.log('Doing ajax submit');
var formAction = $(this).attr("action");
var fdata = new FormData();
var fileInput = $('#uploadfile')[0];
var file = fileInput.files[0];
fdata.append("file", file);
$.ajax({
type: 'post',
url: formAction,
data: fdata,
processData: false,
contentType: false
}).done(function (result) {
// do something with the result now
console.log(result);
if (result.status === "success") {
alert(result.url);
} else {
alert(result.message);
}
});
});
})
Assuming your server side method has a parameter of with name same as the one we used when we created the FormData object entry(file). Here is a sample where it will upload the image to the uploads directory inside wwwwroot.
The action method returns a JSON object with a status and url/message property and you can use that in the success/done handler of the ajax call to whatever you want to do.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
_context = context;
hostingEnvironment = environment;
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
try
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
var url = Url.Content("~/uploads/" + uniqueFileName);
return Json(new { status = "success", url = url });
}
catch(Exception ex)
{
// to do : log error
return Json(new { status = "error", message = ex.Message });
}
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
Sharing the code that worked for me, implementing #Shyju's answer.
View ( Razor Page ):
<form name="UploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
AJAX code added in Site.js (to make it a reusable):
// The function takes Form and the event object as parameter
function SubmitForm(frm, caller) {
caller.preventDefault();
var fdata = new FormData();
var file = $(frm).find('input:file[name="uploadfile"]')[0].files[0];
fdata.append("file", file);
$.ajax(
{
type: frm.method,
url: frm.action,
data: fdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
})
};
if you want to submit the form without using ajax request
var form = document.getElementById('formId');
form.submit();

Unable to fetch Input File in servlet from request object

I have a requirement to fetch the uploaded input file from form and save it into mysql database. Here I am unable to fetch the input file from request object.
My servlet:
#Component(service = Servlet.class, property = {
"service.description=" + "************** Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths=" + "/bin/uploadtestservlet" })
public class UploadTestServlet extends SlingAllMethodsServlet{
#Reference
UploadAdmissionFormService uploadService;
private static final long serialVersionUID = 1L;
private final Logger LOGGER = LoggerFactory
.getLogger(UploadTestServlet .class);
protected void doPost(SlingHttpServletRequest request,
SlingHttpServletResponse response) {
try{
if(ServletFileUpload.isMultipartContent(request)){
List<File> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(File item : multiparts){
LOGGER.info("Name :::"+new File(item.getName()).getName()); //
}
}catch(Exception e){
}
}
My js:
$("#uploadSubmit").click(function(e) {
$.ajax({
type: "POST",
url: "/bin/uploadAdmissionForm",
data: 'passport=' +$('#uploadPhoto').get(0).files.item(0),
success: function(msg) {
},
});
});
HTML:
<form method="POST" enctype="multipart/form-data" id="upload-details-form">
<input type="file" name="uploadPhoto" id="uploadPhoto" class="uploadPhoto">
<div class="upload-photo">
<div class="upload-photo-content">
<h4>UPLOAD PHOTO</h4>
<p>Upload your recent passport size (3.5 x 4.5cm) color photograph (format should be jpg, gif, png, jpeg, bmp and maximum file size alloted is 1 MB)</p>
</div></div><form>
Exception:
Exception occurred in doPost :the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8
Even though I have added enctype="multipart/form-data" at form level, this error is getting throw. Can someone please help me here. Thanks
Your ajax does not specify a file. You have to add processData:false,contentType:false to your method.
$("#uploadSubmit").click(function(e) {
$.ajax({
type: "POST",
url: "/bin/uploadAdmissionForm",
data: new FormData( this ), //this is needed
processData: false, //this is needed
success: function(data) {
//handle return here
},
contentType: false //this is needed
});
});
Here are some links about it:
jQuery AJAX file upload PHP
upload file through ajax
How to upload a file using jQuery.ajax and FormData

form data upload multiple files through ajax together with text fields

Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!
Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']
Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input

How can I submit a form and upload a file using ajax to a spring controller?

I have a form which contains four fields, the file, the name, the type (just a string) and the taskInstanceId.
<form>
<table id="documentDetailsTable">
<tr>
<td>Document Type: </td>
<td><select id="documentType" name="type"> </select></td>
</tr>
<tr>
<td>
Document Name:
</td>
<td>
<input type="text" id="documentName" name="name"/>
</td>
</tr>
<tr id="newFile">
<td>
Choose a file:
</td>
<td>
<input type="file" name="file" />
</td>
</table>
<input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId">
<input id="uploadButton" value="Upload" type="submit"/>
<input class="closeButton" id="closeNew" value="Close" type="button"/>
</form>
If I submit this form it will connect to my FileUploadController and the file will upload.
#RequestMapping(value = "/formTask.do", method = RequestMethod.POST)
public ModelAndView handleFormTaskUpload(#RequestParam("name") String name,
#RequestParam("type") String type,
#RequestParam("file") MultipartFile file,
#RequestParam("taskInstanceId") int taskInstanceId)...//rest of the code
Now I would like to submit this form using jquery/json instead so that I can return a string indicating a successful upload and then display a dialog on the page indicating this. (I don't want to return a new ModelAndView).
So using the same html form I create a new Controller function...
#RequestMapping(value = "/formTask2.json", method = RequestMethod.POST)
public String handleFormTaskUpload2(UploadTaskDocument myNewUpload)).../rest of the code
Now I would like to submit the form above using jQuery. My attempt is here.
This function is called everytime the file is changed.
function prepareUpload(event)
{
files = event.target.files;
}
And this one is called when the form is submitted.
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data;
data = {
documentName: $("#documentName").val(),
documentType: $("#documentType").val(),
taskInstanceId: selectedTaskInstanceId,
uploadedfiles: files
};
var json = JSON.stringify(data);
$.ajax({
url: '/SafeSiteLive/formTask2.json',
type: 'POST',
data: json,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR)
{
if (typeof data.error === 'undefined')
{
// Success so call function to process the form
//submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
The Json data looks like this before it's posted...
But once it reaches the server everything is null...
Ok this might seem a bit different than your solution but I would go forth by doing the following.
As I understand you want to upload the data using ajax to your controller and avoid a post back, and then return a string and nothing but a string. I would do as follows.
You have your form:
<form> //Remove the method type as well as where the post should happen to ensure that you do not have to prevent default behavior
<table id="documentDetailsTable">
<tr>
<td>Document Type: </td>
<td><select id="documentType" name="type"> </select></td>
</tr>
<tr>
<td>
Document Name:
</td>
<td>
<input type="text" id="documentName" name="name"/>
</td>
</tr>
<tr id="newFile">
<td>
Choose a file:
</td>
<td>
<input type="file" name="file" />
</td>
</table>
<input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId">
<input id="uploadButton" value="Upload" onclick('uploadFiles()')/> //Add //the event to your submit button and remove the submit from itself
<input class="closeButton" id="closeNew" value="Close" type="button"/>
</form>
Your JQuery:
//Stays the same I would suggest using a object type and then stringify it as follows
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
//var data = new FormData();
//.each(files, function (key, value)
//{
// data.append(key, value);
//});
//data.append('documentName', $("#documentName").val());
//data.append('documentType', $("#documentType").val());
//data.append('taskInstanceId', $("#taskInstanceId").val());
// Create a objectobject and add the files
var data;
data = {
documentName:$("#documentName").val(),
documentType:$("#documentType").val(),
taskInstanceId:$("#taskInstanceId").val(),
uploadedfiles: files
}
var json = JSON.stringify(data);
$.ajax({
url: '/SafeSiteLive/formTask2.do',
type: 'POST',
data: json,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR)
{
if (typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
In your controller:
As you are working with MVC, please use a Model as it is the correct fashion to catch a parameter.
public String handleFormTaskUpload2(UploadedFile mynewUpload )
{
//rest of code here
}
Your Model will then look something to this.
public class UploadedFile
{
public string documentName{get;set}
public string documentType{get;set}
public string taskInstanceId{get;set}
prop List<byte[]> files {get;set}
}
Hope this helps, please let me know if you still don't understand

XMLHTTPREQUEST send file and parameters [duplicate]

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
I currently do almost the same with both methods but the way in which the data is gathered into an array is different, the data uses .serialize(); but the files use = new FormData($(this)[0]);
Is it possible to combine both methods to be able to upload files and data in one form through Ajax?
Data jQuery, Ajax and html
$("form#data").submit(function(){
var formData = $(this).serialize();
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="data" method="post">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<button>Submit</button>
</form>
Files jQuery, Ajax and html
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="files" method="post" enctype="multipart/form-data">
<input name="image" type="file" />
<button>Submit</button>
</form>
How can I combine the above so that I can send data and files in one form via Ajax?
My aim is to be able to send all of this form in one post with Ajax, is it possible?
<form id="datafiles" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
another option is to use an iframe and set the form's target to it.
you may try this (it uses jQuery):
function ajax_form($form, on_complete)
{
var iframe;
if (!$form.attr('target'))
{
//create a unique iframe for the form
iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
$form.attr('target', iframe.attr('name'));
}
if (on_complete)
{
iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
iframe.load(function ()
{
//get the server response
var response = iframe.contents().find('body').text();
on_complete(response);
});
}
}
it works well with all browsers, you don't need to serialize or prepare the data.
one down side is that you can't monitor the progress.
also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc"
I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working
$(".submitbtn").on("click", function(e) {
var form = $("#Form");
// you can't pass Jquery form it has to be javascript form object
var formData = new FormData(form[0]);
//if you only need to upload files then
//Grab the File upload control and append each file manually to FormData
//var files = form.find("#fileupload")[0].files;
//$.each(files, function() {
// var file = $(this);
// formData.append(file[0].name, file[0]);
//});
if ($(form).valid()) {
$.ajax({
type: "POST",
url: $(form).prop("action"),
//dataType: 'json', //not sure but works for me without this
data: formData,
contentType: false, //this is requireded please see answers above
processData: false, //this is requireded please see answers above
//cache: false, //not sure but works for me without this
error : ErrorHandler,
success : successHandler
});
}
});
this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html i.e.
<input id="fileupload" type="file" name="UploadedFiles" multiple>
public class MyViewModel
{
public HttpPostedFileBase[] UploadedFiles { get; set; }
}
Or shorter:
$("form#data").submit(function() {
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
EDIT: with the new version of JQuery (3.6), you could also try using contentType function argument instead of enctype. Try contentType: multipart/form-data.
For me, it didn't work without enctype: 'multipart/form-data' field in the Ajax request. I hope it helps someone who is stuck in a similar problem.
Even though the enctype was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype without explicit declaration (jQuery 3.3.1).
// Tested, this works for me (jQuery 3.3.1)
fileUploadForm.submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log('Thank God it worked!');
}
}
);
});
// enctype field was set in the form but Ajax request didn't set it by default.
<form action="process/file-upload" enctype="multipart/form-data" method="post" >
<input type="file" name="input-file" accept="text/plain" required>
...
</form>
As others mentioned above, please also pay special attention to the contentType and processData fields.
A Simple but more effective way:
new FormData() is itself like a container (or a bag). You can put everything attr or file in itself.
The only thing you'll need to append the attribute, file, fileName eg:
let formData = new FormData()
formData.append('input', input.files[0], input.files[0].name)
and just pass it in AJAX request. Eg:
let formData = new FormData()
var d = $('#fileid')[0].files[0]
formData.append('fileid', d);
formData.append('inputname', value);
$.ajax({
url: '/yourroute',
method: 'POST',
contentType: false,
processData: false,
data: formData,
success: function(res){
console.log('successfully')
},
error: function(){
console.log('error')
}
})
You can append n number of files or data with FormData.
and if you're making AJAX Request from Script.js file to Route file in Node.js beware of using
req.body to access data (ie text)
req.files to access file (ie image, video etc)
The code below works for me
$(function () {
debugger;
document.getElementById("FormId").addEventListener("submit", function (e) {
debugger;
if (ValidDateFrom()) { // Check Validation
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
debugger;
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function (result) {
debugger;
if (xhr.readyState == 4 && xhr.status == 200) {
debugger;
var responseData = JSON.parse(xhr.responseText);
SuccessMethod(responseData); // Redirect to your Success method
}
};
xhr.send(new FormData(form));
}
}
}
}, true);
});
In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method.
It should work with AJAX Begin form as well.
Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement
I know I am answering late but this is what worked for me
Just to remind, in 2022 you don't need to use jquery. Try js standard Fetch API
var formData = new FormData(this);
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if(response.ok) {
//success
alert(response);
} else {
throw Error('Server error');
}
})
.catch(error => {
console.log('fail', error);
});
This is a solution that I implemented
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
---Solution for DOT NET CORE MVC Implementation---
While looking at this question I though I should right .NET CORE implementation for this because the question is not specific to any backend language.
So guys here is the standalone implementation example.
Objective :- To submit form fields including files and how we can get data in a single model at backend
HTML Code / View Code - Views/Home/Index.cshtml
#{
ViewData["Title"] = "Home Page";
}
<input type="file" id="FileUpload1" multiple />
<div>
<label>Enter First Name :</label>
<input type="text" id="nameText" maxlength="50" />
</div>
<input type="button" id="btnUpload" value="Submit Form with Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append("files", files[i]);
}
// Adding one more key to FormData object
fileData.append('FirstName', $("#nameText").val());
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Backend Code / Controller action method Controllers/HomeController.cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _environment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
{
_logger = logger;
_environment = environment;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadFiles(MyForm myForm)
{
var files = myForm.Files;
// First Name
string name = myForm.FirstName;
// check All files
foreach (IFormFile source in files)
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
string fileWithPath = this.GetPathAndFilename(filename);
// Create directory if not exist
Directory.CreateDirectory(Path.GetDirectoryName(fileWithPath));
using (FileStream output = System.IO.File.Create(fileWithPath))
await source.CopyToAsync(output);
}
return Ok("Success");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public class MyForm
{
public string FirstName { get; set; }
public IList<IFormFile> Files { get; set; }
}
private string EnsureCorrectFilename(string filename)
{
if (filename.Contains("\\"))
filename = filename.Substring(filename.LastIndexOf("\\") + 1);
return filename;
}
private string GetPathAndFilename(string filename)
{
return Path.Combine(_environment.ContentRootPath, "uploadedFiles", filename);
}
}
Full Source Code Repo: https://github.com/rj-learning/DotNetCoreFileUpload
In my case I had to make a POST request, which had information sent through the header, and also a file sent using a FormData object.
I made it work using a combination of some of the answers here, so basically what ended up working was having this five lines in my Ajax request:
contentType: "application/octet-stream",
enctype: 'multipart/form-data',
contentType: false,
processData: false,
data: formData,
Where formData was a variable created like this:
var file = document.getElementById('uploadedFile').files[0];
var form = $('form')[0];
var formData = new FormData(form);
formData.append("File", file);
you can just append them on your formdata, add your files and datas in it.you can read this..
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
for better understanding. you can separately retrieve them $_FILES for your files and $_POST for your data.
<form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button type='button' id='submit_btn'>Submit</button>
</form>
<script>
$(document).on("click", "#submit_btn", function (e) {
//Prevent Instant Click
e.preventDefault();
// Create an FormData object
var formData = $("#form").submit(function (e) {
return;
});
//formData[0] contain form data only
// You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here -->)
var formData = new FormData(formData[0]);
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data: formData,
success: function (response) {
console.log(response);
},
contentType: false,
processData: false,
cache: false
});
return false;
});
</script>
///// otherpage.php
<?php
print_r($_FILES);
?>

Categories

Resources