im have a weird problem whereby my functionality of exporting to excel doesnt seem to work.
im using J-Query and AJAX to pass html data to a http handler which has some simple context.Response code which all seems fine. Anyway, heres my code:
// my hyperlink for user to click
Click Here to Export
my J-Query/AJAX code
<script type="text/javascript">
$(document).ready(function () {
$("#hyperLink").click(function (e) {
var result = $('#output').html();
var newRes = result.replace('\n', '');
$.ajax({
url: "ExportToExcelhandler.ashx",
data: { 'htmlData': newRes },
dataType: "json",
type: "POST",
success: function (data) {
alert(data);
}
});
});
});
</script>
and my handler:
public void ProcessRequest(HttpContext context)
{
string htmlStuff = context.Request["htmlData"];
string trimStart = "";
string trimEnd = "";
if (htmlStuff != null)
{
trimStart = htmlStuff.Substring(75, htmlStuff.Length - 75);
trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
}
string final= trimEnd;
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", "attachment; filename=excelData.xls");
context.Response.ContentType = "application/vnd.ms-excel";
HttpResponse response = context.Response;
context.Response.Output.Write(finalHtmlData);
context.Response.Flush();
context.Response.End();
}
-- Granted, I'm doing some weird things with replace function in my J-Query, and Substring and Remove in my handler; this is because i had to trim my html data so that only the table with the data inside it was included (caused error otherwise). The html data is just report data. So the html data is passed fine to the handler, and it goes through the ProcessRequest method fine, yet doesn't export to excel. Any help would be greatly appreciated, thanks.
Split this into two HTTP handlers, one to generate the Excel data and the second to retrieve the data and have a resource point at it, like this:
GenerateExcelDocument HTTP handler code:
public void ProcessRequest(HttpContext context)
{
string htmlStuff = context.Request["htmlData"];
var docIdentifier = this.GenerateExcelDocument(htmlStuff);
context.Response.ContentType = "text/plain";
context.Response.Write(docIdentifier.ToString("N"));
}
private Guid GenerateExcelDocument()
{
var identifier = Guid.NewGuid();
string trimStart = "";
string trimEnd = "";
if (htmlStuff != null)
{
trimStart = htmlStuff.Substring(75, htmlStuff.Length - 75);
trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
}
// Logic that generates your document and saves it using the identifier
// Can save to database, file system, etc.
return identifier;
}
Now you can call this HTTP handler, like this:
$(document).ready(function () {
$("#hyperLink").click(function (e) {
var result = $('#output').html();
var newRes = result.replace('\n', '');
$.ajax({
url: "GenerateExcelDocument.ashx",
data: { 'htmlData': newRes },
dataType: "json",
type: "POST",
success: function (result) {
window.location.href = '/RetrieveExcelDocument.ashx/' + result;
}
});
});
});
Note: The success callback is where you can hook up the HTML resource to the file retrieval from the server (think href of the anchor tag that worked without passing data to the handler before).
Finally, we need to build the retrieval HTTP handler logic to actually get the Excel document, based upon the identifier returned from the GenerateExcelDocument HTTP handler call, like this:
RetrieveExcelDocument HTTP handler code:
public void ProcessRequest(HttpContext context)
{
var identifier = new Guid(context.Request.Url.Segments[1]);
// Get Excel document content from database, file system, etc. here
var fileContent = GetExcelDocument(identifier);
context.Response.AddHeader("content-disposition",
"attachment; filename=excelData.xls");
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.OutputStream.Write(fileContent, 0, fileContent.Length);
}
Related
i can't really find a way to download a 100mb zip file from the server to the client and also show the progress while downloading. So how will this look for a normal api controller i can add to my server-side project? if lets say i have 3 files i want to download at 50mb each.
i have tried using JSInterop like this, but this is not showing the progress of the file download, and how will i do if i want to download 3 seperate files at the same time?
try
{
//converting file into bytes array
var dataBytes = System.IO.File.ReadAllBytes(file);
await JSRuntime.InvokeVoidAsync(
"downloadFromByteArray",
new
{
ByteArray = dataBytes,
FileName = "download.zip",
ContentType = "application/force-download"
});
}
catch (Exception)
{
//throw;
}
JS:
function downloadFromByteArray(options: {
byteArray: string,
fileName: string,
contentType: string
}): void {
// Convert base64 string to numbers array.
const numArray = atob(options.byteArray).split('').map(c => c.charCodeAt(0));
// Convert numbers array to Uint8Array object.
const uint8Array = new Uint8Array(numArray);
// Wrap it by Blob object.
const blob = new Blob([uint8Array], { type: options.contentType });
// Create "object URL" that is linked to the Blob object.
const url = URL.createObjectURL(blob);
// Invoke download helper function that implemented in
// the earlier section of this article.
downloadFromUrl({ url: url, fileName: options.fileName });
// At last, release unused resources.
URL.revokeObjectURL(url);
}
UPDATE:
if im using this code, it will show me the progress of the file. But how can i trigger it from my code? This way does not do it. But typing the url does.
await Http.GetAsync($"Download/Model/{JobId}");
Controller
[HttpGet("download/model/{JobId}")]
public IActionResult DownloadFile([FromRoute] string JobId)
{
if (JobId == null)
{
return BadRequest();
}
var FolderPath = $"xxxx";
var FileName = $"Model_{JobId}.zip";
var filePath = Path.Combine(environment.WebRootPath, FolderPath, FileName);
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", FileName);
}
UPDATE 2!
i have got it download with progress and click with using JSInterop.
public async void DownloadFiles()
{
//download all selectedFiles
foreach (var file in selectedFiles)
{
//download these files
await JSRuntime.InvokeAsync<object>("open", $"Download/Model/{JobId}/{file.Name}", "_blank");
}
}
Now the only problem left is.. it only downloads the first file out of 3.
I am passing Json Data from Angular JS Controller. The Json Data contains two strings called name attribute and comment attribute and a list of files. The controller code for angular is given below:
app.controller("demoController", function ($scope, $http) {
//1. Used to list all selected files
$scope.files = [];
//2. a simple model that want to pass to Web API along with selected files
$scope.jsonData = {
name: "Sibnz",
comments: "This is a comment"
};
//3. listen for the file selected event which is raised from directive
$scope.$on("seletedFile", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
});
//4. Post data and selected files.
$scope.save = function () {
$http({
method: 'POST',
url: "http://localhost:51739/PostFileWithData",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files.length; i++) {
formData.append("file" + i, data.files[i]);
}
return formData;
},
data: { model: $scope.jsonData, files: $scope.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
};
});
In the Web API, controller I am receiving the JSON data by using the following code:
[HttpPost]
[Route("PostFileWithData")]
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles");
Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
var model = result.FormData["jsonData"];
var g = result.FileData;
if (model == null)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
//TODO: Do something with the JSON data.
//get the posted files
foreach (var file in result.FileData)
{
//TODO: Do something with uploaded file.
var f = file;
}
return Request.CreateResponse(HttpStatusCode.OK, "success!");
}
When I debug the code, I find that the JSON data is populating the var model and var g variables. I want to extract the name and comment attributes from the Json Data and store them in the Database. And also want to copy the file into /App_Data/Uploadfiles directory and store the file location in the database.
You need to create a model in your Web API and deserialize JSON data to this model, you can use Newtonsoft.Json NuGet package for that
Install-Package Newtonsoft.Json
class DataModel
{
public string name { get; set; }
public string comments { get; set; }
}
In Web API controller
using Newtonsoft.Json;
HttpRequest request = HttpContext.Current.Request;
var model = JsonConvert.DeserializeObject<DataModel>(request.Form["jsonData"]);
// work with JSON data
model.name
model.comments
To work with files
// Get the posted files
if (request.Files.Count > 0)
{
for (int i = 0; i < request.Files.Count; i++)
{
Stream fileStream = request.Files[i].InputStream;
Byte[] fileBytes = new Byte[stampStream.Length];
// Do something with uploaded file
var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles/");
string fileName = "image.jpg";
File.WriteAllBytes(root + fileName, stampBytes);
// Save only file name to your database
}
}
I creating a custom MultipartStreamProvider to store files in Azure File Storage as part of a Lift & Shift effort of a legacy application. The client is using AngularJS on the front end and WebAPI on the backend. When I am trying to use the MultipartStreamProvider, I need to implement GetStream to return a stream for it to write to. I am using cloudFile.OpenWrite which asks for the size of the stream/file that will be written to it. However, in GetStream, the ContentDisposition.Size is empty. Is there a way I can either make the AngularJS send the content size for each file or on the backend, maybe I can dig the size of the file stream from somewhere else? Any help would be greatly appreciated. Thanks!
MultipartStreamProvider
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
// For form data, Content-Disposition header is a requirement
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
Console.WriteLine(files.Count);
if (contentDisposition != null)
{
// create default filename if its missing
contentDisposition.FileName = (String.IsNullOrEmpty(contentDisposition.FileName) ? $"{Guid.NewGuid()}.data" : contentDisposition.FileName);
// We won't post process files as form data
_isFormData.Add(false);
CloudMultipartFileData fileData = new CloudMultipartFileData(headers, _fileRepository.BaseUrl, contentDisposition.FileName);// your - aws - filelocation - url - maybe);
_fileData.Add(fileData);
var azureStream = _fileRepository.GetWriteStream(contentDisposition.Size, _relativeDirectory, fileData.FileName);
return azureStream;
// We will post process this as form data
_isFormData.Add(true);
}
throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part..");
}
Actual Call to Azure
public override Stream GetWriteStream(long? fileSize, string relativeDirectory, string filename)
{
var combinedRelativeDirectory = GetCloudDirectory(relativeDirectory);
CloudFile cloudFile = combinedRelativeDirectory.GetFileReference(filename);
return cloudFile.OpenWrite(fileSize, null, null);
}
AngularJS File Upload Code
/********************************** Add/Upload Photos **************************************/
$scope.$watch('files', function (files) {
$scope.formUpload = false;
console.log(files);
if (files != null) {
for (var i = 0; i < files.length; i++) {
$scope.errorMsg = null;
(function (file) {
upload(file);
})(files[i]);
}
}
});
function upload(file) {
file.upload = Upload.upload({
url: window.location.origin + "/api/mydocs/uploadfile?storeFolder=" + $scope.attachmentFolder + "&storeId=" + $scope.storeId + "&userId=" + $scope.currentUser.UserId,
method: 'POST',
headers: {},
fields: {},
file: file
});
I wound up manually adding the file size to the header
function upload(file) {
file.upload = Upload.upload({
url: window.location.origin + "/api/mydocs/uploadfile?storeFolder=" + $scope.myFolder + "&clientId=" + $scope.clientId,
method: 'POST',
headers: { 'file-info':file.name + "-/" + file.size },
fields: {},
file: file
});
And then in the constructor, I use that to create a lookup table:
public MyCloudMultipartFormDataStreamProvider(string relativeDirectory, IEnumerable<string> lookupInfo)
{
NewFileNames = new Dictionary<string, string>();
_fileRepository = new CloudFileRepository();
_relativeDirectory = relativeDirectory;
_uploadedFilesLookup = new Dictionary<string, long>();
foreach (var fileInfo in lookupInfo)
{
var values = Regex.Split(fileInfo, #"-/");
_uploadedFilesLookup.Add(values[0], Int64.Parse(values[1]));
}
}
Then grab the file's size out of the lookup table and pass that to my GetWriteStream method
var azureStream = _fileFacade.GetWriteStream(_uploadedFilesLookup[fileName],
_relativeDirectory, fileData.FileName, out newFileName);
I am uploading my pictures using uplodifiy. here is the my codes are below.but
inside the Upload.ashx handler,I coulnt get the submitted values(Id and foo values).they return null values.
how can I solve this problem .thank you .
I have a code like this
$(document).ready(function () {
var id = "55";
var theString = "asdf";
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader': 'Upload.ashx',
'swf': 'uploadify/uploadify.swf',
'script': 'Upload.ashx',
'cancelImg': 'images/cancel.png',
'folder': 'upload',
'multi': true,
'buttonText': 'RESIM SEC',
'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
'auto': false,
'scriptData': { 'id': id, 'foo': theString}
,onAllComplete: function (event, data) {
}
});
});
and my ashx file like this;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
//I tryed both way to get values both both return null values.
string pwd1 = context.Request["Id"];
string pwd2 = context.Request.Form["Foo"];
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string id = context.Request["id"];
string savepath = "";
string tempPath = "";
tempPath = context.Request["folder"];
//If you prefer to use web.config for folder path, uncomment below line:
//tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
savepath = context.Server.MapPath(tempPath);
string filename = postedFile.FileName;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);
string ext = System.IO.Path.GetExtension(filename);
string resimGuid = Guid.NewGuid().ToString();
..........
..........
Use formData with Post method
Extra data can be passed to the script as either a querystring if the method option is set to ‘get’, or via the headers if it’s set to ‘post’. This is all done with the help of the formData option. Depending on what you’ve set as the method option (‘post’ or ‘get’), you can retrieve the information sent in the formData option at server side.
For more detils Please refer Passing Extra Data
i want to generate the table of contents from database.. using jquery ajax in asp.net, i am using sql server 2008 as a backend. for this i created a webmethod in my normal aspx page. and on the clientside wrote the ajax script to fetch records but when i loop through the results, i gets message undefined and nothing happens.. i want to generate table out of the records from database below is my webmethod.
[WebMethod]
public static Poll[] GetPollDetailed()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("sp_SelectQuestion", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#siteid", 3);
DataTable dt = new DataTable();
da.Fill(dt);
List<Poll> _poll1 = new List<Poll>();
foreach (DataRow row in dt.Rows)
{
Poll _poll = new Poll();
_poll.QuestionID = Convert.ToInt32(row["questionID"]);
_poll.Question = row["question"].ToString();
_poll.Published = Convert.ToInt32(row["visible"]);
_poll.Date = Convert.ToDateTime(row["Added_Date"]);
}
return _poll1.ToArray();
}
public class Poll
{
public Poll() { }
private int _questionId, _published;
private string _question;
private DateTime _date;
public int QuestionID
{
get { return _questionId; }
set { _questionId = value; }
}
public string Question
{
get { return _question; }
set { _question = value; }
}
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
public int Published
{
get { return _published; }
set { _published = value; }
}
}
</code>
and below is my script.
<code>
$(this).load(function () {
$.ajax({
type: "POST",
url: "AddPollAJax.aspx/GetPollDetailed",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
error: function (data) {
alert("Error: " + data.responseText);
}
});
});
</code>
can any one please help me to resolve this issue, i am very curious about it.
Assuming your service is configured correctly to return JSON data, issue lies at your js code fragment for success callback i.e.
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
MS ASP.NET script services always return a wrapped JSON due to security issues, so you need unwrap resultant JS object to get the actual data. So you need to change the code to
success: function (result) {
var data = result.d; // actual response will be in this property
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
BTW, ASP.NET Web Services are now considered legacy, so I will suggest you to migrate to WCF services instead.