converting image into byte[] asp.net mvc - javascript

I need to store the image in my database in byte[]
I am sending the image from Javascript to mvc controller using ajax
In my javascript
var files = $("#MyImage").get(0).files;
formData.append('files', files);
in my MVC Controller
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
Is it a correct way to store the image or I am doing this wrong?
please suggest

You can post HttpPostedFileBase on your razor.
if (upload != null)
{
using (var inputStream = upload.InputStream)
{
var memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
var data = memoryStream.ToArray();
}
The method signature should be like this
[HttpPost]
public ActionResult Foo(HttpPostedFileBase upload)
{
}
And your razor side:
#using (Html.BeginForm("Foo", "ControllerName", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
}

Related

How to send files to aspx with ajax

Im trying to make an ajax post request to an aspx that is supposed to handle my file uploads. However when i read the requests Files, it contains no files.
public partial class SaveFile : System.Web.UI.Page
{
public bool isSaved = false;
[HttpPost]
protected void Page_Load(object sender, EventArgs e)
{
//Get the files from the request
var request = HttpContext.Current.Request;
var files = request.Files; <---- this is empty when it should have files
//temporary path until put on server
string basePath = #"C:\Users\ClonePC\Desktop\UploadedFiles";
//write each file to the disk and save it to the mongodatastructure
foreach (HttpPostedFile file in files) {
SavedFile sf = new SavedFile();
var fileType = file.ContentType;
var fileNameOnDisk = $#"{sf.UID}.{fileType}";
var fullPath = $#"{basePath}\{fileNameOnDisk}";
sf.FileName = file.FileName;
sf.FilePath = fullPath;
var byteStream = file.InputStream;
BinaryReader br = new BinaryReader(byteStream);
byte[] byteArr = br.ReadBytes((Int32)byteStream.Length);
File.WriteAllBytes(fullPath, byteArr);
}
isSaved = true;
}
}
this is my ajax request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
console.log(this.response);
};
xhr.open('POST', PathProvider.GetRooPath() + "/SaveFile.aspx");
console.log(formData.getAll("files"));
xhr.send(filesAdded[0]);<--any generic file

Downloading excel file from web api using closedxml

I can't get it to work to download an excel file that was created by closedxml through web API.
If I save the file on the server it looks good, but as soon as I put it in a stream and return it to the web api, then only a corrupt file is recieved in the browser.
As suggested on several posts I use httpResponseMessage, but also in the browser the filename in the header never arrives.
We are using:
"Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net461
"ClosedXML" version="0.88.0" targetFramework="net461"
WebAPI Code:
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Parcel List");
MemoryStream fs = new MemoryStream();
wb.SaveAs(fs);
fs.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(fs.GetBuffer());
result.Content.Headers.ContentLength = fs.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "List" + "_" + DateTime.Now.ToShortDateString() + ".xlsx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
Here the javascript code:
context.$http.post(config.get_API_URL() + 'api_call', excel_list,
{responseType: 'application/octet-stream'})
.then(
success_function,
error_function)
}
success_function:
function(response) {
var headers = response.headers;
var blob = new Blob([response.body],
{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
);
window.open(window.URL.createObjectURL(blob));
}
I could successfully download a workbook with this code now:
using ClosedXML.Excel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace ClosedXML.Extensions.WebApi.Controllers
{
public class ValuesController : ApiController
{
public IHttpActionResult Get(int id)
{
return new TestFileActionResult(id);
}
}
public class TestFileActionResult : IHttpActionResult
{
public TestFileActionResult(int fileId)
{
this.FileId = fileId;
}
public int FileId { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
var ms = new MemoryStream();
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().Value = this.FileId;
wb.SaveAs(ms);
ms.Seek(0, SeekOrigin.Begin);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(ms);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "test.xlsx";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentLength = ms.Length;
ms.Seek(0, SeekOrigin.Begin);
}
return Task.FromResult(response);
}
}
}
Have a look at the Mvc extension package at https://www.nuget.org/packages/ClosedXML.Extensions.Mvc/
PS: I've been told I have to disclaim this everytime. I'm the maintainer of ClosedXML and ClosedXML.Extensions.Mvc.
The problem seems to be that the response type for the web api call has to be {responseType: 'arraybuffer'} instead of {responseType: 'application/octet-stream'}
context.$http.post('api-url', excel_list,
{responseType: 'arraybuffer'})
.then(
success_function,
error_function)
}
Thanks anyhow for your quick help

Javascript gzip decompression

I want do decompress images in JavaScript. I have compressed the images with C# using gzip. How do I decompress gzipped data in JavaScript?
C# code
public static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return memory.ToArray();
}
}
First of all you have to close the GZipStream when you are done with it.
public static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
gzip.Close();
}
return memory.ToArray();
}
}
You can use pako for decompressing in javascript.
var base64Data = "COMPRESSED_BASE64_GZIP";
var compressData = atob(base64Data);
compressData = compressData.split('').map(function (e) {
return e.charCodeAt(0);
});
var originalText = pako.ungzip(compressData, {to:"string"});

Excel Export in ASP.NET Web Service

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.

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