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

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;
}

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

jquery $.ajax call for MVC actionresult which returns JSON triggers .error block

I have the following $.ajax post call. It would go through the action being called but then it would trigger the "error" block of the function even before the actionresult finishes. Also, it seems to reload the whole page after every pass.
var pnameVal = '<%: this.ModelCodeValueHelper().ModelCode%>';
var eidVal = '<%: ViewBag.EventId %>';
var dataV = $('input[ name = "__RequestVerificationToken"]').val();
var urlVal = '<%: Url.Action("New") %>';
alert('url > ' + urlVal);
alert('pname - ' + pnameVal + ' eid - ' + eidVal + ' dataV = ' + dataV);
$.ajax({
url: urlVal,
//dataType: "JSONP",
//contentType: "application/json; charset=utf-8",
type: "POST",
async: true,
data: { __RequestVerificationToken: dataV, pname: pnameVal, eId: eidVal },
success: function (data) {
alert('successssesss');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert('dammit');
}
})
.done(function (result) {
if (result.Success) {
alert(result.Message);
}
else if (result.Message) {
alert(' alert' + result.Message);
}
alert('done final');
//$('#search-btn').text('SEARCH');
waitOff();
});
This is the action
[HttpPost]
public ActionResult New(string pname, int eid)
{
var response = new ChangeResults { }; // this is a viewmodel class
Mat newMat = new Mat { "some stuff properties" };
Event eve = context.Events.FirstOrDefault(e => e.Id == eid);
List<Mat> mats = new List<Mat>();
try
{
eve.Mats.Add(newMat);
icdb.SaveChanges();
mats = icdb.Mats.Where(m => m.EventId == eid).ToList();
response.Success = true;
response.Message = "YES! Success!";
response.Content = mats; // this is an object type
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
response.Content = ex.Message; // this is an object type
}
return Json(response);
}
Btw, on fiddler the raw data would return the following message:
{"Success":true,"Message":"Added new Mat.","Content":[]}
And then it would reload the whole page again. I want to do an ajax call to just show added mats without having to load the whole thing. But it's not happening atm.
Thoughts?
You probably need to add e.preventDefault() in your handler, at the beginning (I am guessing that this ajax call is made on click, which is handled somewhere, that is the handler I am talking about).

Javascript post jsonObject with Image Binary

I have a HTML form for filling the personal profile, which includes String and Images. And I need to post all these data as JsonObject with one backend api call, and the backend requires the image file sent as binary data. Here is my Json Data as follow:
var profile = {
"userId" : email_Id,
"profile.name" : "TML David",
"profile.profilePicture" : profilePhotoData,
"profile.galleryImageOne" : profileGalleryImage1Data,
"profile.referenceQuote" : "Reference Quote"
};
and, profilePhotoData, profileGalleryImage1Data, profileGalleryImage2Data, profileGalleryImage3Data are all image Binary data(Base64).
And here is my post function:
function APICallCreateProfile(profile){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
$.ajax({
url: requestUrl,
type: 'POST',
data: profile,
dataType:DATA_TYPE,
contentType: CONTENT_TYPE_MEDIA,
cache:false,
processData:false,
timeabout:API_CALL_TIMEOUTS,
success: function (response) {
console.log("response " + JSON.stringify(response));
var success = response.success;
var objectData = response.data;
if(success){
alert('CreateProfile Success!\n' + JSON.stringify(objectData));
}else{
alert('CreateProfile Faild!\n'+ data.text);
}
},
error: function(data){
console.log( "error" +JSON.stringify(data));
},
failure:APIDefaultErrorHandler
})
.done(function() { console.log( "second success" ); })
.always(function() { console.log( "complete" ); });
return false;
}
But still got failed, I checked the server side, and it complains about the "no multipart boundary was found".
Can anyone help me with this, thanks:)
Updates:
var DATA_TYPE = "json";
var CONTENT_TYPE_MEDIA = "multipart/form-data";
I think I found the solution with vineet help. I am using XMLHttpRequest, and didn't set the requestHeader, but it works, very strange. But hope this following can help
function APICallCreateProfile(formData){
var requestUrl = BASE_URL + API_URL_CREAT_PROFILE;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200){
console.log( "profile:" + xhr.responseText);
}else if (xhr.readyState==500){
console.log( "error:" + xhr.responseText);
}
}
xhr.open('POST', requestUrl, true);
// xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=----WebKitFormBoundarynA5hzSDsRj7UJtNa");
xhr.send(formData);
return false;
}
Why to reinvent the wheel. Just use Jquery Form Plugin, here. It has example for multipart upload as well.
You just need to set input type as file. You will receive files as input stream at server (off course they will be multipart)

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,

Sending other data besides File in Ajax Post in Spring MVC

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

Resources