How to pass file object through ajax sumbit with spring mvc controller - javascript

I am trying to pass the file object through jquery ajax submit.
JSP code
<div id="import-file">
<input type="file" id="file"/>
<table>
<tr><td><input type="radio" name="type" value="csv"></td><td>CSV File</td></tr>
<tr><td><input type="radio" name="type" value="excel"></td><td>Excel spread sheet</td></tr>
<tr><td><input type="radio" name="type" value="tab"></td><td>Tab delimited</td></tr>
</table>
</div>
Java script code
var type = $($('input:radio:checked')[0]).val();
var file = $("#file")[0].files[0];
alert($("#file")[0].files[0].name);
$.ajax({
data :{
"file" : file,
"type" : type
},
type: "POST",
url: "fileupload.htm",
success: function(data){
alert(data);
},
error:function(err){
alert(err);
}
});
finally here is my spring controller code:
#RequestMapping(value="fileupload.htm",method=RequestMethod.POST )
public #ResponseBody String uploadFile(#RequestParam String type, #RequestParam("file") MultipartFile file){
logger.info("file type : "+type + "file is "+file.toString());
return "SUCCESS";
}
Am getting NS_NOINTERFACE: Component does not have requested interface [nsIDOMBlob.slice] error in my firebug console.

I have solved it like this:
JavaScript code
var formData = new FormData($('form')[0]);
console.log("form data "+formData);
$.ajax({
url: 'fileupload.htm',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
},
error: function(err){
alert(err);
}
});
JSP Code
<form action="fileupload.htm" method="post" enctype="multipart/form-data" name="fileinfo">
<input type="file" name="fileName" id="file"/>
</form>
Spring Controller:
#RequestMapping(value="fileupload.htm",method=RequestMethod.POST )
public #ResponseBody String uploadFile(#RequestParam("fileName") MultipartFile file){
try{
logger.info("file is "+file.toString());
}catch(Exception e){
return "error occured "+e.getMessage();
}
}
Hope it helps some body.

Related

How to pass an array of "FormData" via ajax and access in Laravel controller

# I just want to know how to send this array the controller by requete ajax
var dataPanier=[];
function addarray(objser)
{
dataPanier.push(objser);
}
$('.target').click(function() {
var btn_name=$(this).attr("name");
switch(btn_name) {
case 'FormPVC':
var dataformPVC = new FormData(),
form_data = $('#'+btn_name).serializeArray();
$.each(form_data, function (key, input) {
dataformPVC.append(input.name, input.value);
});
dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
addarray(dataformPVC);
break;
.
.
.
more . . .
I am attempting to send multiple forms data as an array by ajax to a Larave controller.
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: array ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
$("#btnTest").click(function(){
var formData = $('#frm1, #frm2').serialize();
console.log(formData);
$.ajax({
method: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frm1">
<input name="n1" type="text"/>
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<form id="frm2">
<input name="n1" type="text" />
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<input type="button" id="btnTest" value="send"/>
As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:
var formData = $('#form1, #form2').serialize();
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div>.

How to send form data to a Spring controller using ajax

I have a Sudoku board generated with thymeleaf and I want to send all the tile values as a double array to a Spring controller or as a String.
<form class="box" id="sudokuBoard">
<table>
<tr th:each="row: ${board}">
<td th:each="value: ${row}">
<div th:switch="${value}">
<input th:case="0" style="width:30px;height:30px;text-align:center" type = "text" maxlength="1" value="0">
<input th:case="*" style="width:30px;height:30px;text-align:center;background-color:lightgreen" type = "text" th:value="${value}" readonly>
</div>
</td>
</tr>
</table>
<input type="submit"> Check Solution </input>
</form>
I've tried to use the serialize() function but it doesn't send anything or I'm doing something wrong.
<script>
$("#sudokuBoard").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
$.ajax({
type: "POST",
url: "/sudoku",
dataType: 'json',
data: form.serialize(),
success: function(msg)
{
console.log("data sent");
}
});
});
</script>
This is the Spring controller
#RequestMapping(value = "/sudoku", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
String checkBoardStatus(#RequestBody String jsonString){
System.out.println("json string: " + jsonString);
return "sudoku";
}
You can use this example, where success will be your callback method
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result) {},
dataType: dataType
});
#RequestMapping(value = "/sudoku", method = RequestMethod.POST)
String checkBoardStatus(Map<String,Object> params){
System.out.println("Request Params: " + params);
return "sudoku";
}
User above code.. Try to use a DTO class to map request body instead of Map and do not use #RequestBody annotation

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

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>

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 to pass Image from jsp to controller in Spring MVC

Send Image file from html to controller page in Spring MVC
File to upload: <input type="file" name="UploadFile" id="file"><br>
<input type="submit" value="Upload" onclick="sortByDateeeee()">
Get this image file in javascript and passed to controller.
function sortByDateeeee(){
var request = document.getElementById("file").value;
var url=CONTEXT_ROOT+"/login/uploadFile";
$.ajax({
type: "POST",
url: url,
data:{
"request": request
},
success: function(response){
//alert(response);
}
});
}
Following controller
#ResponseBody
#RequestMapping(value="/uploadFile", method=RequestMethod.POST)
#HttpMethodConstraint(value = "POST")
public String uploadFileHandler(#RequestParam(required=false) HttpServletRequest request)
System.out.println("request: "+request);
}
My problem is unable to call controller.. please help me to get out of this.
<input type="file" name="file" />
<script type="text/javascript">
function sortByDateeeee() {
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
console.log("form data " + formData);
$.ajax({
url : 'login/uploadFile',
data : formData,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
alert(data);
},
error : function(err) {
alert(err);
}
});
}
</script>
and in your controller
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody String doUpload(#RequestParam("file") MultipartFile multipartFile) {
return "Uploaded: " + multipartFile.getSize() + " bytes";
}
I think the url will be only
var url="uploadFile";
. You may not need to add rest of the things

Categories

Resources