Sending other data besides File in Ajax Post in Spring MVC - ajax

I am trying to send some other data with the file in ajax post
var fileInput = document.getElementById('file');
var creditcardid = document.getElementById('creditcardid');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('creditcardid', 'creditcardid');
formData.append('file', file);
$.ajax({
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(response) {
document.getElementById('statusMsg').innerHTML="<fmt:message key="fileUpload.success"/>";
Success();
}
In controller i am writing the code as
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public #ResponseBody String fileUpload(#RequestParam(value = "creditcardid")Long creditcardid,#RequestParam(value = "file") MultipartFile file,Model model, HttpServletRequest request) {
String response = "generic.unexpectederror";
try {
model.addAttribute("message", "File '" + file.getOriginalFilename() + "' uploaded successfully");
logger.info("Size of the file is " + file.getSize());
logger.info("Name of the file is " + file.getOriginalFilename());
response = "fileUpload.success";
} catch (DataIntegrityViolationException e) {
response = "fileUpload.error";
logger.error(ExceptionUtils.getStackTrace(e));
}
return response;
}
But my code is not calling controller. Please let me know how to receive both the data and the file. Thanks

Related

Unable to receive object FormData from JQuery Ajax in WebApi method: HttpContext.Current.Request.Files[0] returns null

I have tried many suggestions from stack overflow earlier threads, but the issue still do not seem to be resolving.
Client Side Code:
var file = document.getElementById('MainForm_main_panel_company_code_change_file').files[0];
var formData = new FormData();
formData.append("file", file);
data = '[0, {"data":{"args":"'+formData+'"}}]';
$.ajax({
url: 'Control/MainForm.main_panel.company_code_change/GetData',
type: 'POST',
data: data,
contentType: false,
processData: false,
dataType: 'json',
success: function (result) {
if (result.msg === undefined) {
JSMessage.show("Success", "Report Generated Successfully");
} else
JSMessage.show("Error", "Report Generation Failed:" +result.msg.text);
}
Note: If I don't mention data = '[0, {"data":{"args":"......., it throws error: 'data is required'
Server Side Code:
public class CompanyCodeChangeArg
{
public string args;
public CompanyCodeChangeArg()
{
F<IMNull<CompanyCodeChangeArg>>.Instance.SetNull(this);
}
}
[HttpPost]public string GetData(CompanyCodeChangeArg arg)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
var fileName = Path.GetFileName(filebase.FileName);
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Uploads/"), fileName);
filebase.SaveAs(path);
return "";
}
Please help me here, I need to upload the file using WebApi Method and JQuery AJAX,
Tried various suggestions on stack overflow but it did not worked

How to download a file from an AJAX response

Im making an AJAX POST request to a spring controller and getting returned an byte array as the response. I want to make it downloadable. What is the best approach to take?
Heres my implementation :
var params = [[${params}]];
$("#download-button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/patient-listing/excel",
data: JSON.stringify(params),
success: function(result) {
var byteArray = result;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));
a.download = "file.XLSX";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
},
error: function(result) {
console.log('error');
}
});
});
In here even though the file is downloaded there is no data.
Controller :
#PostMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getEmployeeReportXlsx(#RequestBody Param param) {
logger.info("Generating Excel report of param : " + param);
final byte[] data = poiService.getExcelFile(param);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=case-data-report.xlsx");
header.setContentLength(data.length);
return new ResponseEntity<>(data, header, HttpStatus.OK);
}
You can simply download excel without AJAX request,
Change POST method to GET method using #GetMapping
#GetMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
in thymeleaf ,
<a class="sidebar-element" th:href="#{/patient-listing/excel}">
Generate Excel
</a>

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 :

Posting Image Data From Ajax to WebAPI

I am trying to pass a image dat to a web API method using example code I found on here http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2 and I am finding that MultipartFormDataStreamProvider.FileData is always empty. Why might this be? Also, is this the right approach to be taking? Are there options? I am trying to pass only a single image.
The Call
var t = new FormData();
t.append('file-', file.id);
t.append('filename', file.name);
t.append('Size', file.size);
$.ajax({
url: sf.getServiceRoot('mySite') + "upload/PostFormData",
type: "POST",
data: t,
contentType: false,
processData: false,
beforeSend: sf.setModuleHeaders
}).done(function (response, status) {
alert(response);
}).fail(function (xhr, result, status) {
alert("error: " + result);
});
});
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
I could get fileData properly when posted via form,
as in sample goes # WebAPI upload error. Expected end of MIME multipart stream. MIME multipart message is not complete
Good Luck,

Download File from C# through Web Method via Ajax call?

I have tried to download the file from the server through the webmethod
but it has not work for me.
my code as below
[System.Web.Services.WebMethod()]
public static string GetServerDateTime(string msg)
{
String result = "Result : " + DateTime.Now.ToString() + " - From Server";
System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString()) + "\\" + "Default.aspx");
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
//HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Flush();
Response.End();
return result;
}
and my ajax call code is as below
<script type="text/javascript">
function GetDateTime() {
var params = "{'msg':'From Client'}";
$.ajax
({
type: "POST",
url: "Default.aspx/GetServerDateTime",
data: params,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
},
error: function (err) {
}
});
}
</script>
and i have called this function in button click..
i don't know how to download the file with other methods
Please suggest me if any other methods available or give the correction in the same code.
Thanks to all..
A WebMethod does not have control of the current response stream, so this is not possible to do this way. At the time you call a web method from javascript, the response stream is already delivered to the client, and there is nothing you can do about it.
An option to do this is that the WebMethod generates the file as a physical file somewhere on the server, and then returns the url to the generated file to the calling javascript, which in turn uses window.open(...) to open it.
In stead of generating a physical file, you can call some GenerateFile.aspx that does about what you initially tried in your WebMethod, but do it in Page_Load, and call window.open('GenerateFile.aspx?msg=From Clent') from javascript.
Instead of calling a Web Method it would be a better idea to use a generic handler (.ashx file) and put your code for downloading the file in the ProcessRequest method of the handler.
This is Ajax Call
$(".Download").bind("click", function ()
{
var CommentId = $(this).attr("data-id");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TaskComment.aspx/DownloadDoc",
data: "{'id':'" + CommentId + "'}",
success: function (data) {
},
complete: function () {
}
});
});
Code Behind C#
[System.Web.Services.WebMethod]
public static string DownloadDoc(string id)
{
string jsonStringList = "";
try
{
int CommentId = Convert.ToInt32(id);
TaskManagemtEntities contextDB = new TaskManagementEntities();
var FileDetail = contextDB.tblFile.Where(x => x.CommentId == CommentId).FirstOrDefault();
string fileName = FileDetail.FileName;
System.IO.FileStream fs = null;
string path = HostingEnvironment.ApplicationPhysicalPath + "/PostFiles/" + fileName;
fs = System.IO.File.Open(path + fileName, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.End();
fs = null;
//jsonStringList = new JavaScriptSerializer().Serialize(PendingTasks);
}
catch (Exception ex)
{
}
return jsonStringList;
}

Resources