How to retrieve uploaded file using ajax on java server side? - ajax

I am using struts2 framework on server side. I am uploading a file using
server side :
<s:file name="fTU" id="fTU"/>
<input type="submit" value ="ok" onclick="upload()">
client side :
function upload(){
var file = document.getElementById("fTU");
try {
this.xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
this.xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
this.xml = null;
}
}
if(!this.xml && typeof XMLHttpRequest != "undefined")
this.xml = new XMLHttpRequest();
if (!this.xml){
this.failed = true;
}
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
xml.open("POST", "", true);
xml.setRequestHeader("Content-Type", "false");
xml.send(formData); /* Send to server */
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
alert(xml.statusText);
}
}
}
How to fetch the uploaded file object on struts2 server side?
It is going in server side class and I am trying to retrieve file by using request.getParameter(upload) but it is giving null.

function upload(form){
var fd = new FormData(form);
$.ajax({
url : "<url-value>", //this is the actionName
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
},
error: function(xhr, status, error){
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
}

I think you missed to add the Action Link in the xml.open() method. Take a look at the MDN to see some examples.
How does your Action-class look like? Have you defined a File field named upload with getter/setters?
Please also check, that your browser supports the FormData element, see question.
I also would suggest you to use a library like jQuery to simplify the Javascript code.
Action
public class FileUpload extends ActionSupport {
File myFile;
public String execute() {
//do some preparations for the upload
return SUCCESS;
}
public String upload() {
//only here the myFile is filled with data
return SUCCESS;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public File getMyFile() {
return myFile;
}
}
struts.xml
<!-- init method to show the form -->
<action name="fileForm" class="...FileUpload">
<result name="success">fileupload.jsp</result>
</action>
<!-- upload method to upload the file -->
<action name="fileUpload" class="...FileUpload" method="upload">
<result name="success">fileupload.jsp</result>
</action>
JSP
<s:form enctype="multipart/form-data" method="post" name="fileinfo" action="fileUpload">
<s:file name="myFile"/>
</s:form>
<input type="submit" onClick="upload()" value="OK">
Javascript (taken from the MDN example above)
function upload() {
var fd = new FormData(document.querySelector("form"));
$.ajax({
url : "fileUpload", //this is the actionName
type: "POST",
data: fd,
processData: false,
contentType: false
});
return false; //to stop submitting the form
}
I have not tested this code, so please change it or add comments if something doesn't work.

Related

Partial view page for create,edit,delete in asp.net mvc4

How to upload the image in asp.net mvc4.images save in local folder,images path name save to database.
I would say use Valum's AJAX File Uploader
here is how I'd done that
[HttpGet]
public ActionResult PictureUpload()
{
return View();
}
[HttpPost]
public ActionResult PictureUpload( string qqfile)
{
var path = Server.MapPath("~/App_data/Files/");
var file = string.Empty;
try
{
var stream = Request.InputStream;
if (String.IsNullOrEmpty(Request["qqfile"]))
{
// IE
HttpPostedFileBase postedFile = Request.Files[0];
if (postedFile != null) stream = postedFile.InputStream;
file = Path.Combine(path, qqfile);
}
else
{
//Webkit, Mozilla
file = Path.Combine(path, qqfile);
}
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(file, buffer);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, "application/json");
}
return Json(new { success = true }, "text/html");
}
**THIS GIVEN HTML and Javascript need uploaderjs file and css file from Valums website **
Index
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
<script src="~/Scripts/fileuploader.js"></script>
<script type="text/javascript">
var uploader = new qq.FileUploader({
// pass the dom node (ex. $(selector)[0] for jQuery users)
element: document.getElementById('file-uploader'),
// path to server-side upload script
action: '/FileUpload/File',
onComplete: function(data) {
alert(data);
},
});
</script>
Hope this will help

Ajax post a JSON model to ASP.Net MVC4 with Anti-forgery token

I am submitting json model through ajax post. Its not working after adding user validation.
var token = $('input[name=""__RequestVerificationToken""]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: '/SalesQuotation/Create',
cache: false,
headers: headers,
data: JSON.stringify(salesquotation),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
async: false,
success: function (result) {
if (result.Success == "1") {
window.location.href = "/SalesQuotation/Create";
}
else {
alert(result.ex);
}
}
});
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create(SalesQuotation salesquotation)
{
try
{
if (ModelState.IsValid)
{
if (salesquotation.QuotationId > 0)
{
var CurrentsalesQuotationSUb = db.SalesQuotationSubs.Where(p => p.QuotationId == salesquotation.QuotationId);
foreach (SalesQuotationSub ss in CurrentsalesQuotationSUb)
db.SalesQuotationSubs.Remove(ss);
var CurrentsalesQuotationDta = db.DTATrans.Where(p => p.QuotationId == salesquotation.QuotationId);
foreach (DTATran ss in CurrentsalesQuotationDta)
db.DTATrans.Remove(ss);
foreach (SalesQuotationSub ss in salesquotation.salesquotationsubs)
db.SalesQuotationSubs.Add(ss);
foreach (DTATran ss in salesquotation.dtatrans)
db.DTATrans.Add(ss);
db.Entry(salesquotation).State = EntityState.Modified;
}
else
{
db.SalesQuotations.Add(salesquotation);
}
db.SaveChanges();
}
}
catch (Exception ex)
{
return Json(new { Success = 0, ex = "Unable to save... " + ex.Message.ToString()});
}
return Json(new { Success = 1, ex = new Exception("Saved successfully.").Message.ToString() });
}
View:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<input name="__RequestVerificationToken" type="hidden"
value="H4zpQFvPdmEdGCLsFgeByj0xg+BODBjIMvtSl5anoNaOfX4V69Pt1OvnjIbZuYrpgzWxWHIjbng==" />
The server return
What could be missing in my method. Please advice....
Attribute selectors should only have a single set of quotes around them. Your code has two quotes on each side.
This:
var token = $('input[name=""__RequestVerificationToken""]').val();
should be this:
var token = $('input[name="__RequestVerificationToken"]').val();
Use [ValidateJsonAntiForgeryToken] attribute in action method.

Uploading files to tastypie with Backbone?

Checked some other questions and I think my tastypie resource should look something like this:
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
class ImageResource(MultipartResource, ModelResource):
image = fields.FileField(attribute="image")
Please tell me if that's wrong.
What I don't get, assuming the above is correct, is what to pass to the resource. Here is a file input:
<input id="file" type="file" />
If I have a backbone model img what do I set image to?
img.set("image", $("#file").val()); // tastypie doesn't store file, it stores a string
img.set("image", $("#file").files[0]); // get "{"error_message": "'dict' object has no attribute '_committed'" ...
What do I set my backbone "image" attribute to so that I can upload a file to tastypie via ajax?
You may override sync method to serialize with FormData api to be able to submit files as model's attributes.
Please note that it will work only in modern browsers. It worked with Backbone 0.9.2, I advise to check the default Backbone.sync and adopt the idea accordingly.
function getValue (object, prop, args) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ?
object[prop].apply(object, args) :
object[prop];
}
var MultipartModel = Backbone.Model.extend({
sync: function (method, model, options) {
var data
, methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
}
, params = {
type: methodMap[method],
dataType: 'json',
url: getValue(model, 'url') || this.urlError()
};
if (method == 'create' || method == 'update') {
if (!!window.FormData) {
data = new FormData();
$.each(model.toJSON(), function (name, value) {
if ($.isArray(value)) {
if (value.length > 0) {
$.each(value, function(index, item_value) {
data.append(name, item_value);
})
}
} else {
data.append(name, value)
}
});
params.contentType = false;
params.processData = false;
} else {
data = model.toJSON();
params.contentType = "application/x-www-form-urlencoded";
params.processData = true;
}
params.data = data;
}
return $.ajax(_.extend(params, options));
},
urlError: function() {
throw new Error('A "url" property or function must be specified');
}
});
This is excerpt from upload view, I use <input type="file" name="file" multiple> for file uploads so user can select many files. I then listen to the change event and use collection.create to upload each file.
var MultipartCollection = Backbone.Collection.extend({model: MultipartModel});
var UploadView = Backbone.View.extend({
events: {
"change input[name=file]": "changeEvent"
},
changeEvent: function (e) {
this.uploadFiles(e.target.files);
// Empty file input value:
e.target.outerHTML = e.target.outerHTML;
},
uploadFiles: function (files) {
_.each(files, this.uploadFile, this);
return this;
},
uploadFile: function (file) {
this.collection.create({file: file});
return this;
}
})

File upload is not working in spring using jquery-ajax

This is my form :
<form name="CIMtrek_Compliance_Daily_Shipments" enctype="multipart/form-data">
<input type="file" id="CIMtrek_comments" name="CIMtrek_comments" value="" />
<button id="upload" onclick="uploadCommentFile()">Upload</button>
</form>
and this is my ajax call using jquery :
function uploadCommentFile(){
$("#upload").live("click", function() {
var file_data = $("#CIMtrek_comments").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
//form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
type: 'POST',
url: "/CIMtrek_Compliance_Daily_Shipments_FileUpload",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: {
uploadFile: file_data
},
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
}
})
})
}
and this is my spring controller :
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(#RequestParam("uploadFile") CommonsMultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName="";
try {
MultipartFile file = uploadItem;
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
System.out.println("size::" + file.getSize());
fileName = request.getRealPath("") + "/WEB-INF/resources/Attachment"+ file.getOriginalFilename();
System.out.println("path : "+request.getRealPath("") + "/WEB-INF/resources/Attachment");
outputStream = new FileOutputStream(fileName);
System.out.println("fileName:" + file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName =file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
but i get the following exception when i click on upload button :
HTTP Status 400 -
The request sent by the client was syntactically incorrect.
what could be the problem, Please help me to identify.
Best Regards.
Follow this one it helped and solved my problem :

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

Resources