I am trying to make an upload page which takes file to upload. I am using Spring framework here my query is on Upload button I am calling a JavaScript method which should send my file to controller using jQuery AJAX. Is there any way to pass this through JavaScript?
Following is the code which I am trying.
<body>
<div style="text-align: center; margin-top: 60px;">
<form enctype="multipart/form-data">
Select file:
<input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
<div style="text-align: center; margin-top: 100px;">
<input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
</div>
</form>
</div>
</body>
JS:
<script language="Javascript">
function uploadAttachment(){
var Name = jQuery('#Name option:selected').text();
jQuery.post('upload',{Name:Name}
function(data){
if(data==1)
alert("success");
else
alert("failed");
});
}
</script>
on controller.java page following is the code written
#RequestMapping(value = "upload", method=RequestMethod.POST)
public #ResponseBody String upload(HttpServletRequest request, HttpServletResponse response,
#RequestParam("Name") String Name){
System.out.println(Name);
}
If you are in fact seeking a pure javascript way to upload an image/file, then the following tutorial from 2009 will tell you exactly how to do that:
http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html
I ran into this when I wanted to add basic-authentication to a form submission, without enabling cookies. E.g. when you have username/password fields with your filename, file, etc fields.
Hope this helps!
I think you can try the following code to upload file with javascript.
function uploadAttachment(){
$('#fileAttachment').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
timer = setInterval(function() {
if ($('#fileAttachment').val() != '') {
clearInterval(timer);
$.ajax({
url: 'YOUR_UPLOAD_URL',
type: 'post',
dataType: 'json',
data: new FormData($('#fileAttachment').closest('form')[0]),
cache: false,
contentType: false,
processData: false,
success: function(response){
}
});
}
}, 500);
}
You need to replace YOUR_UPLOAD_URL with your server upload URL.
Related
I am trying to upload the file, it is working on my local system, but not working in the server.
<form class="form-group row" style="height:100px;" id="uploading" method="post" enctype="multipart/form-data">
<div class="col-md-10" align="center">
<div class="form-group row" align="center">
<label class="col-md-2 form-control-label"> File to upload:</label>
<div class="col-md-10" >
<div class="input-group">
<input type="file" class="filestyle" data-buttonName="btn-primary" name="upload" id="upload" accept="*"/>
</div>
</div>
</div>
<div class="form-group row" id="buttonzone">
<div class="col-sm-14">
<div class="input-group">
<button type="submit" class="btn btn-success" id="upload" style="margin-left: 96px;">
<i class="fa fa-cloud-upload"></i> Upload</button>
<button type="button" class="btn btn-danger" id="cancel" ><i class="fa fa-ban"></i> Cancel</button>
</div>
</div>
</div>
</div>
</form>
$("form#uploading").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url : '/uploadController/upload',
type: 'POST',
data: formData,
async: false,
beforeSend: beforeSendHandler,
success: function (data){
var msg=data.msg;
var obj=data.obj;
if(data.success == true){
$('#successmsg').html(msg);
$('.alert-success').show();
$('.alert-danger').hide();
setTimeout(function(){
$(".alert-success").alert('close');
}, 10000);
}else{
$('#errmsg').html(msg);
$('.alert-danger').show();
$('.alert-success').hide();
setTimeout(function(){
$(".alert-danger").alert('close');
}, 10000);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Java code:
#RequestMapping(value = "/uploadController/upload",headers=("content-type=multipart/*"), method = RequestMethod.POST)
public #ResponseBody StatusResponse totxnsUpload(#RequestParam("upload") MultipartFile upload, HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchFieldException, SecurityException{
logger.debug(" file upload controller");
//my logic here
}
I am getting this in browser console:
{
"timestamp":1495781126083,
"status":400,
"error":"Bad Request",
"exception":"org.springframework.web.bind.MissingServletRequestParameterException",
"message":"Required MultipartFile parameter 'upload' is not present",
"path":"/uploadController/upload"
}
But it is working on out of server, I don't what is the problem.
the parameter "upload" as seen in #RequestParam("upload") MultipartFile upload
is a required parameter. If it is working in some systems it means that it is getting a parameter named "upload". In your case it fails because it is not present in the request.
You do have an input named upload in your form though. But I can see you are trying to send form data using ajax. Can you see the request in browser dev tools network tab?
Also place a breakpoint in your totxnsUpload method and see if you are getting two form submit requests (one standard and one with ajax)
for debugging purposes you can set upload parameter to optional in your Java code with this replacement #RequestParam(value = "upload", required = false) MultipartFile upload
With that being said. If the exact same code is working on your machine but not working on the server, you might need to configure your context. Take a look at this How to use HttpServletRequest#getParts() in a servlet filter running on Tomcat?
I'm creating a JSP/Servlet web application and I'd like to upload a file to a servlet via Ajax. How would I go about doing this? I'm using jQuery.
I've done so far:
<form class="upload-box">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error" />
<input type="submit" id="upload-button" value="upload" />
</form>
With this jQuery:
$(document).on("#upload-button", "click", function() {
$.ajax({
type: "POST",
url: "/Upload",
async: true,
data: $(".upload-box").serialize(),
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
$("#upload-error").html("Couldn't upload file");
}
});
});
However, it doesn't appear to send the file contents.
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden <iframe> and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing, such as the jQuery Form plugin (an example).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JavaScript disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's, with the help of the jQuery Form plugin, just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How can I upload files to a server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JavaScript disabled (as of now, it is mostly the older mobile browsers which have JavaScript disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return an Ajax response (e.g. write JSON or XML).
} else {
// Return a regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 drag and drop file upload to Java Servlet and Send a file as multipart through XMLHttpRequest.
Monsif's code works well if the form has only file type inputs. If there are some other inputs other than the file type, then they get lost. So, instead of copying each form data and appending them to FormData object, the original form itself can be given to the constructor.
<script type="text/javascript">
var files = null; // when files input changes this will be initialised.
$(function() {
$('#form2Submit').on('submit', uploadFile);
});
function uploadFile(event) {
event.stopPropagation();
event.preventDefault();
//var files = files;
var form = document.getElementById('form2Submit');
var data = new FormData(form);
postFilesData(data);
}
function postFilesData(data) {
$.ajax({
url : 'yourUrl',
type : 'POST',
data : data,
cache : false,
dataType : 'json',
processData : false,
contentType : false,
success : function(data, textStatus, jqXHR) {
alert(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('ERRORS: ' + textStatus);
}
});
}
</script>
The HTML code can be something like following:
<form id ="form2Submit" action="yourUrl">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br>
<input id="fileSelect" name="fileSelect[]" type="file" multiple accept=".xml,txt">
<br>
<input type="submit" value="Submit">
</form>
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>
This code works for me.
I used Commons IO's io.jar, Commons file upload.jar, and the jQuery form plugin:
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
<form id="upload-form" class="upload-box" action="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "../../web/Images/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..
this is html page.
<head>
<script type="text/javascript" src="json2.js"></script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
<div data-role="content" data-inset="true"> <img src="images/logo_hdpi.png"/>
</div>
</div>
<div data-role="content" data-theme="c">
<form name="form" method="post" onsubmit="return validate()">
<div class="logInner">
<div class="logM">Already have an account?</div>
<div class="grouped insert refb">
<div class="ref first">
<div class="input inputWrapper">
<input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
</div>
<div class="input inputWrapper">
<input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
</div> <input type="submit" data-inline="true" value="Submit" onclick="json2()">
<p>Forgot Password
</p>
</div>
</div>
<div class="logM">New user? Create refer Account</div>
<input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
</form>
</div>
</div>
<p style="text-align: center;">© refer247 2013</p>
</div>
</body>
this is json2.js
function json2()
{
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
//var parsed = jsonString.evalJSON( true );
alert(json1["username"]);
alert(json1["password"]);
};
so tell me how to send the json data to that url n obtain some response like if email
id is already exist if u registering with that id ..then give some error
like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...
You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.
var objectData =
{
Username: document.getElementById('userid').value,
Password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "your url with method that accpects the data",
dataType: "json",
data: {
o: objectDataString
},
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
And your method can have only one parameter of string type.
[HttpPost]
public JsonResult YourMethod(string o)
{
var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
}
$.ajax({
url: urlToProcess,
type: httpMethod,
dataType: 'json',
data:json1,
success: function (data, status) {
var fn = window[successCallback];
fn(data, callbackArgs);
},
error: function (xhr, desc, err) {
alert("error");
},
});
function addProductById(pId,pMqty){
$.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
alert(json.msg);
});
}
Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.
and after successful completion it return message in alert which is set in that servlet in json.
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
data: {param1: json1},
})
.done(function(response) {
console.log("success");
alert(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
on the server you can receive you json and decode it like so:
$myjson=json_decode($_POST['param1']);
I have a form in JSP in the following manner :
<form id="provision-field" method="post" action="${pageContext.request.contextPath}/myServlet">
<fieldset>
<ol class="fields">
<li>
<label for="field1">field1</label>
<input type="text" id="field1" "
value="<%= field1 %>"
/>
<span class="description">
<span class="optional">Optional</span>
</span>
</li>
</ol>
</fieldset>
<div class="actions">
<button type="submit" name="Submit">
Submit form
</button>
Cancel
</div>
</form>
I have a js snippet on click of the submit button does the following
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: field,
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
When I just use the form element (ie take out the js code) , I can reach my servlet but none of my form parameters are passed . when I try using the js code , the ajax request does not work . could someone point to me how this should be correctly done .
The servlet code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Inside the post function");
logger.info(request.getParameter("data");
}
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: {
data :field
},
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
Inside servelt following code in doPost method :
Assuming that you have primary knowledge of HttpServlet...
request.getParameter("data");
I am sharing small Ajax with Servlet tutorial , which may help you for further problem... Download Link- AJAX Servlet Tutorial
data: { field1:field1Value } send like this
and then access request.getParameter("field1"); in servlet
As form submission method is post method="post", you need to make sure you are fetching request values in doPost(request, response) method
I am trying to get the response from an Ajax call into a html label. I am using a tomcat server. Ia m able to see the description returned form the server however how do i get the responses into the lable text. Under is what i have tried:
Jquery
function GetDescription(Id){
$.ajax({
type:'GET',
url:'getDescription.htm',
data:{dId:Id},
dataType: 'json',
success: function (data) {
$('.TypeDesc').text = data.responseText;
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var typeId = document.getElementsByClassName("TypeId")[i].value;
GetDescription(typeId);
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
});
html
</head>
<body>
<div id ="content">
<c:forEach items="${object}" var="i">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${i.fName} ${i.lName}
<input type="hidden" id="photo" value="${i.photo}" class="photos"/>
<input type="hidden" id="Number" value="${i.Number}" />
<input type="text" class="TypeId" value="${i.citizenTypeId}"/>
<label class="TypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>
The problem is that you're telling jQuery you're expecting JSON:
dataType: 'json',
...and so it's (trying to) parse the response as JSON and pass you an object, but then you're trying to use it like a raw XHR object.
If you want the text, remove the dataType or change it to dataType: 'text', and then use data which will be a string.
Your other problem is that text is a function, not a property, so you need to call it.
So:
dataType: 'text',
success: function (data) {
$('.TypeDesc').text(data);
}
Please add this to the parameters of the ajax call
success: function(data) {
$('.TypeDesc').each(function(){
$(this).text(data);
});
}
You need to give the lable a unique ID like id="TypeDesc{i}" or something different.
So you can refer to it something like this:
$('#TypeDesc{i}').text = data.responseText;