Excel Export in ASP.NET Web Service - javascript

I have this ASP.Net Web Application and in one of my Pages I'm using JQuery JQGrid, I want to be able to export the JQGrid to Excel Sheet, so using JavaScript I Collected the Values in an Array and then called a WebService to fill the values in a DataGrid, I successfully done all that, except for the exporting in the WebService no file download appears, and this is my WebService code:
[WebMethod]
public void GetData(object[] Values)
{
DT_ToFill.Columns.Add("CaseID");
DT_ToFill.Columns.Add("SR");
foreach (object Value in Values)
{
Dictionary<string, object> DictVals = new Dictionary<string, object>();
DictVals = (Dictionary<string, object>)Value;
string CaseID = DictVals["CaseID"].ToString();
string SR = DictVals["SR"].ToString();
object[] Obj = new object[2] { CaseID, SR };
DT_ToFill.Rows.Add(Obj);
}
ExportToExcel(DT_ToFill, Context.Response);
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
public void ExportToExcel(DataTable dt, HttpResponse Response)
{
GridView GridView1 = new GridView();
GridView1.DataSource = dt;
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "inline;filename=Schedule_ExcelSheet.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.UTF8;
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(ht);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void VerifyRenderingInServerForm(Control control)
{
}
Help Please...
Thanks

Sounds like you are sending the excel file back as the response to the ajax request? If so, I don't think you can make a file download work through ajax.
Maybe send the data via ajax like you are doing now, but then do either a new window or an iframe (append it to document.body) and set the src to be a url that returns the excel file. That should trigger the file download. This is what I usually do.

Related

How do i make a JS code send an array to a JAVA code and make the JS receive data from that JAVA code

Ok, so I've been trying to pass longitude and latitude to JS code and then I want the JS code to send an array of location (pairs of longitude and latitude) back to the JAVA code. I've managed to follow this guide Reading from and Writing to a URLConnection but I can't find its opposing pair of code that will help me send the and receive data from the JS to JAVA. The code so far is below:
import java.net.*;
import java.io.*;
public class URLReader {
/* This one is responsible of sending any data that will be sent to the javascript code*/
URL javascript;
public URLReader() throws MalformedURLException{
javascript = new URL("http://www.oracle.com/");
}
public void send(String longitude, String latitude) throws Exception{
String lon = URLEncoder.encode(longitude, "UTF-8");
String lat= URLEncoder.encode(latitude, "UTF-8");
URLConnection connection = javascript.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("longitude =" + lon);
out.write("latitude =" + lat);
out.close();
}
/* This one is responsible of recieving any data that will be recieved from the javascript code*/
public String[] recieve() throws Exception{
String myArray[] = {};
URLConnection yc = javascript.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
return myArray;
}
}
The variable Latlng is the variable I want to send to my Android Studio code
latlng = {lat: parseFloat(position.coords.latitude), lng: parseFloat(position.coords.longitude)};

Downloading a File Via Angular $.http POST

I am trying to download a zipped file that my server generates in my UI. I am at a loss as to how to get the file to download though. We have it setup so that we can download with window.open where we pass the url and it opens a blank page. We need to do a POST where it has a body now. I havent seen a way to send that along with a window.open. Does anyone have any pointers on how i can get access to the returned file?
Here is my current code...
#RequestMapping(method = RequestMethod.POST, value = "/archives/download", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Integer> getArchive(HttpServletResponse response, #RequestBody List<GeneratedReport> reportList) {
System.out.println(reportList.get(0).getFileLocation());
List<String> filesToDownload = new ArrayList<>();
reportList.stream().forEach(e -> filesToDownload.add(e.getFileLocation()));
filesToDownloadAndZip(response, filesToDownload, "zipped_file.zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=zipped_file.zip");
return new ResponseEntity<Integer>(200, HttpStatus.OK);
}
private void filesToDownloadAndZip(HttpServletResponse response, List<String> filesToDownload, String archiveFileName) {
try {
ByteArrayOutputStream baos = FileIO.CreateArchive(filesToDownload);
if (baos != null && baos.size() > 0) {
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=" + archiveFileName);
response.setContentType("application/zip");
response.setContentLength(baos.size());
baos.writeTo(response.getOutputStream());
response.flushBuffer();
} else {
LOG.debug("File was null or size 0, try again");
}
} catch(Exception ex)
{
LOG.debug(ex.getMessage());
}
}
The js i have is.....
$http.post('api/archives/download', $scope.downloadItems)
.success(function(data, status, headers, config) {
//I dont know what to do here..... :(
})

Uploading PDF from jsPDF with AJAX using binary data

I am attempting to pass a PDF I have generated on frontend javascript using jsPDF to a Spring Framework MVC backend. Below is the front end code I have written:
var filename = "thefile";
var constructURL = '/daas-rest-services/dashboard/pdfPrintUpload/' + filename;
var url = restService.getUrl(constructURL);
var fileBytes = btoa(pdf.output());
$http.post(url, fileBytes).success(function(data) {
console.log(data);
})
.error(function(e, a) {
console.log(e);
console.log(a);
});
The pdf variable has been generated properly and can confirm is opens correctly when calling pdf.save("filename"). Below is the Java code which has been written on the Spring MVC backend for this call:
#RequestMapping(method = RequestMethod.POST, value = "/pdfPrintUpload/{documentName}")
public #ResponseBody String postPrintDocument(#PathVariable String documentName, #RequestParam byte[] fileBytes) {
String methodName = "postPrintDocument";
if(logger.isLoggable(Level.FINER)){
logger.entering(CLASS_NAME, methodName);
}
String check;
if(fileBytes != null){
check = "not null";
} else {
check = "null ";
}
//Decoding the bytestream
//Save to file location
//return file location
String returnValue = "HI " + documentName + " " + check;
if (logger.isLoggable(Level.FINER)) {
logger.exiting(CLASS_NAME, methodName);
}
return returnValue;
}
Each time I make a request, I am getting 400 Errors telling me:
Error 400: Required byte[] parameter 'fileBytes' is not present
I can confirm in the request payload that a large amount of data is being transmitted, however the backend does not seem to want to accept the parameter.
The purpose of doing this is that I want to be able to get the data from the pdf and then decode it on the backend so I can later publish the pdf to a location on the server. Is there something I am missing in my code for these requests to keep failing, and is there an easier more efficient way to achieve this functionality?
The solution was changing the #RequestParam to #RequestBody. #RequestParam is a parameter which is sent in the path.
#RequestParam vs #PathVariable
Try using ng-file-upload. The link and the examples are available on the link
ng-file-upload
for the sever side code try using this
#RequestMapping(value = "/pdfPrintUpload")
#ResponseBody
public void postPrintDocument(#RequestParam("file") MultipartFile file) {
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(/*path to save file*/);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
os.write(buffer, 0, length);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}

How to call a custom action result from Javascript

I have a custom ActionResult that I pass in a url string to and it will stream a file back to me. How would I call this from Javascript file? Since I have to pass a string I don't think I can use jQuery's $.post() or .ajax() methods but I could be wrong. I also can not use Razor's #Html.ActionLink method for reasons involving the ? Here is my code.
public class ReportResult : ActionResult
{
private readonly string _fileName;
public ReportResult(string fileName)
{
_fileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
var cd = new ContentDisposition
{
FileName = _fileName,
Inline = false
};
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
response.Headers["Content-Disposition"] = cd.ToString();
using (var client = new WebClient())
using (var stream = client.OpenRead(_fileName))
{
stream.CopyTo(response.OutputStream);
}
}
}
The Controller Method that references it.
public ActionResult DownloadPdf(string filePath)
{
return new ReportResult(filePath);
}
So the reason why I was having issues with the file opening up in a window rather than downloading was due to the Controller and Action method part of the url string getting cut off before it was getting passed to location.href in the Javascript. Below is the new Javascript that will open the url and immediately download the PDF file.
location.href = "/Controller/DownloadPdf?filePath=" + pdfUrl;
Thanks to #SLacks in the comments for some guidance.

Upload a file on Button click in asp

I am working on classic ASP with WinCE OS. I want to upload a file from WinCE and Save in the local machine. Please share the necessary JScript function for file upload which i can put it in a include file. Thank you.
Better way is to use any JavaScript library.. like jQuery..
Here are the file upload examples..
http://pixelcone.com/jquery/ajax-file-upload-script/
How can I upload files asynchronously?
Cheers :)
I have no information about asp classic but I have used Asp.net and you can use asp to receive file in order to upload file from wince use can develop app using c# here is an example.
Its client WinCE Application Code Function Upload(string Path, String FileName) takes File Path and File Name as Input and Post it to web page
#region Upload
public bool Upload(string FilePath, string FileName)
{
string Url = "HTTP://test.mtsonweb.com/fileupload.ashx"; // Change it to your page name
string BytesConfirmedReceived = "";
int BytesSent = 0;
bool Ret = false;
ASCIIEncoding encoding = new ASCIIEncoding();
try
{
if (File.Exists(FilePath +"\\"+ FileName) == false) { return true; }
//FileInfo oInfo = new FileInfo(FilePath + "\\" + FileName);
//BytesSent = Convert.ToInt32(oInfo.Length.ToString());
Url += "?myfile=" + FileName.Trim();
FileStream fr = new FileStream(FilePath + "\\" + FileName, FileMode.Open);
BinaryReader r = new BinaryReader(fr);
byte[] FileContents = r.ReadBytes((int)fr.Length);
BytesSent = FileContents.Length;
r.Close();
fr.Close();
WebRequest oRequest = WebRequest.Create(Url);
oRequest.Method = "POST";
oRequest.Timeout = 15000;
oRequest.ContentLength = FileContents.Length;
Stream oStream = oRequest.GetRequestStream();
BinaryWriter oWriter = new BinaryWriter(oStream);
oWriter.Write(FileContents);
oWriter.Close();
oStream.Close();
WebResponse oResponse = oRequest.GetResponse();
BytesConfirmedReceived = new StreamReader(oResponse.GetResponseStream(),
Encoding.Default).ReadToEnd();
oResponse.Close();
if (BytesSent.ToString() == BytesConfirmedReceived.Trim())
{
Ret = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Ret;
}
#endregion
Now of you page you can handle file uploaded using script whatever you want, I have used asp.net with c# as back-end and below is the source of page:
<%# WebHandler Language="C#" Class="FileUpload" %>
using System;
using System.Xml;
using System.Data;
using System.Web;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
public class FileUpload : IHttpHandler
{
public void ProcessRequest(HttpContext oContext)
{
int BytesSent = 0;
//string LocalPath = #"C:\Inetpub\wwwroot\";
string MyFile = "";
try
{
MyFile = oContext.Request["myfile"].ToString().Trim();
MyFile = HttpContext.Current.Server.MapPath("~/Demo/Files/" +
ASCIIEncoding encoding = new ASCIIEncoding();
BytesSent = oContext.Request.TotalBytes;
Class1 obj = Class1.GetInstance();
obj.FileName = MyFile;
obj.FileLength = BytesSent;
byte[] InComingBinaryArray =
oContext.Request.BinaryRead(oContext.Request.TotalBytes);
obj.Data = InComingBinaryArray;
if (File.Exists(MyFile) == true)
{
File.Delete(MyFile);
}
FileStream fs = new FileStream(MyFile, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(InComingBinaryArray);
w.Close();
fs.Close();
FileInfo oInfo = new FileInfo(MyFile);
long a = (long)BytesSent;
oContext.Response.Write(oInfo.Length.ToString());
}
catch (Exception err) { oContext.Response.Write(err.Message); }
}
public bool IsReusable { get { return true; } }
}

Categories