Convert file received from jquery to byte array - c#

I need help in converting a file received from a jquery ajax to byte array. I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. Here is my
handler code:
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string fileType = file.ContentType;
string strFileName = fileName;
FileStream fs = new FileStream("~/Temp/" + strFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] imagebytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
DBAccess dbacc = new DBAccess();
dbacc.saveImage(imagebytes);
string msg = "{";
msg += string.Format("error:'{0}',\n", string.Empty);
msg += string.Format("msg:'{0}'\n", strFileName);
msg += "}";
context.Response.Write(msg);
}
I'm saving the file to a folder within a project then trying to retrieve that file and save it to the database. I can assure you that the image is being saved to the temp folder. The problem is with the line with (*) the file path is wrong. This is the file path that is being retrieved. "'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Temp\2012-06-03 01.25.47.jpg'.". The temp folder is located locally inside my project and I want to retrieved the image within that folder. How can I set the file path to my desired location? Or is there another way to convert a file to byte array after retrieving it from a jquery ajax call?
Credits to these articles:
Save and Retrieve Files from SQL Server Database using ASP.NET
Async file upload with jQuery and ASP.NET

Just these 3 lines will do:
int filelength = file.ContentLength;
byte[] imagebytes = new byte[filelength ];
file.InputStream.Read(imagebytes , 0, filelength );

using (var stream = upload.InputStream)
{
// use stream here: using StreamReader, StreamWriter, etc.
}

Related

c# files downloaded with httpwebrequest and cookies get corrupted

I am trying to make a program which is able to download files with URI(URL) using httpwebrequest and cookies(for credential information to keep login status).
I can download files with following code but files get corrupted after being downloaded.
when I download xlsx file(on the web page) into text file at local drive, I see some part of numbers and words from an original file in a corrupted file, therefore I assume I have reached to the right file.
however, when I download xlsx file(on the web page) in xlsx file at local drive, it seems like it fails to open saying
excel cannot open the file 'filename.xlsx' because the file format or
file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file.
Is there any way I can keep fully original file content after I download?
I attach a part of result content as well.
private void btsDownload_Click(object sender, EventArgs e)
{
try
{
string filepath1 = #"PathAndNameofFile.txt";
string sTmpCookieString = GetGlobalCookies(webBrowser1.Url.AbsoluteUri);
HttpWebRequest fstRequest = (HttpWebRequest)WebRequest.Create(sLinkDwPage);
fstRequest.Method = "GET";
fstRequest.CookieContainer = new System.Net.CookieContainer();
fstRequest.CookieContainer.SetCookies(webBrowser1.Document.Url, sTmpCookieString);
HttpWebResponse fstResponse = (HttpWebResponse)fstRequest.GetResponse();
StreamReader sr = new StreamReader(fstResponse.GetResponseStream());
string sPageData = sr.ReadToEnd();
sr.Close();
string sViewState = ExtractInputHidden(sPageData, "__VIEWSTATE");
string sEventValidation = this.ExtractInputHidden(sPageData, "__EVENTVALIDATION");
string sUrl = ssItemLinkDwPage;
HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(sUrl);
hwrRequest.Method = "POST";
string sPostData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" + sViewState + "&__EVENTVALIDATION=" + sEventValidation + "&Name=test" + "&Button1=Button";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bByteArray = encoding.GetBytes(sPostData);
hwrRequest.ContentType = "application/x-www-form-urlencoded";
Uri convertedURI = new Uri(ssDwPage);
hwrRequest.CookieContainer = new System.Net.CookieContainer();
hwrRequest.CookieContainer.SetCookies(convertedURI, sTmpCookieString);
hwrRequest.ContentLength = bByteArray.Length;
Stream sDataStream = hwrRequest.GetRequestStream();
sDataStream.Write(bByteArray, 0, bByteArray.Length);
sDataStream.Close();
using (WebResponse response = hwrRequest.GetResponse())
{
using (sDataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(sDataStream);
{
string sResponseFromServer = reader.ReadToEnd();
FileStream fs = File.Open(filepath1, FileMode.OpenOrCreate, FileAccess.Write);
Byte[] info = encoding.GetBytes(sResponseFromServer);
fs.Write(info, 0, info.Length);
fs.Close();
reader.Close();
sDataStream.Close();
response.Close();
}
}
}
}
catch
{
MessageBox.Show("Error");
}
}
StreamReader is for dealing with text data. Using it corrupts your binary data(excel file).
Write sDataStream directly to file. For ex.
sDataStream.CopyTo(fs)
PS: I prepared a test case (using similar logic) to show how your code doesn't work
var binaryData = new byte[] { 128,255 };
var sr = new StreamReader(new MemoryStream(binaryData));
var str3 = sr.ReadToEnd();
var newData = new ASCIIEncoding().GetBytes(str3); //<-- 63,63
Just compare binaryData with newData

File Stream file saving

I have an image file in Canvas element that I get in code behind in asp.net. now I want to save it to a folder in my project but file stream always saves it to c drive. What do I do?
[WebMethod()]
public void SaveUser(string imageData)
{
//Create image to local machine.
string fileNameWitPath = path + "4200020789506" + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
// Save fileNameWitPath variable to Database.
}
Here is an example of how I save files to an Images folder in my project directory.
var fileName = "4200020789506.png";
var base64String = SOME_REALLY_LONG_STRING;
using (var s = new MemoryStream(Convert.FromBase64String(base64String)))
using (var f = new FileStream(Path.Combine(Server.MapPath("~/Images"), fileName), FileMode.Create, FileAccess.Write))
{
s.CopyTo(f);
}
Here's what I do and it works well. For you, filePath/filename = fileNameWitPath. Do this for each file you have. Hope it works for you. If you need further info, Id be glad to help.
using (var stream = File.Create(filePath + filename))
{
attachment.ContentObject.DecodeTo(stream, cancel.Token);
}
I can only imagine your path variable points to your C:\ drive.
You need to set the path variable equal to the location you want, for instance:
public void SaveUser(string imageData)
{
path = #"C:\YourCustomFolder\"; // your path needs to point to the Directory you want to save
//Create image to local machine.
string fileNameWitPath = path + "4200020789506" + ".png";
//chekc if directory exist, if not, create
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
// Save fileNameWitPath variable to Database.
}
I also included a Check to see if your directory exists, and if it does not, it will create a folder called 'YourCustomFolder' on your C drive, where it will save images.
If you would like to save your image to a folder in your project, I would recommend using Server.MapPath(~/YourFolderInApplication)

Sharepoint to ASP.net MVC file download

I am quite ashamed to ask this question but somehow I am missing something.
Scenario
There is a sharepoint instance
There is a document list in sharepoint with three files
I have a asp.net MVC Portal which connects with Sharepoint instance
In a view it shows the list of files (3 in my case)
When user clicks on the item, the file is to be downloaded.
Problem
The file is downloaded but when you try to open it, word says the file downloaded is corrupt.
I have googled it and tried every variation of code. Only variation that works is to save the file on server and then download it to the client which as you know is not feasible
this is my code
As mentioned above the Sharepoint login,authentication etc all works correctly
fileref is the sharepoint path of the file
len is retrieved from Sharepoint
//int len= int.Parse(oListItemDoc.FieldValues["File_x0020_Size"].ToString());
string filePath = fileRef;
ClientContext clientContext = new ClientContext(GetSharePointUrl());
clientContext = SharepointAuthorisation(clientContext);
if (!string.IsNullOrEmpty(filePath))
{
var cd = new System.Net.Mime.ContentDisposition
{
FileName = Path.GetFileName(fileRef),
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
byte[] fileArr=DownloadFile(title, clientContext, filePath,len,extension, "");
//FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef.ToString());
//byte[] arr = new byte[len];
//fileInfo.Stream.Read(arr, 0, arr.Length - 1);
//return arr;
Response.AppendHeader("Content-Disposition", cd.ToString());
//return new FileStreamResult(fileInfo.Stream, "application /octet-stream");// vnd.openxmlformats-officedocument.wordprocessingml.document");
return File(fileArr, "application/docx" , Path.GetFileName(fileRef));
}
else
{
return null;
}
public byte[] DownloadFile(string title, ClientContext clientContext, string fileRef, int len, string itemExtension, string folderName)// Renamed Function Name getdownload to DownloadFiles
{
if (itemExtension == ".pdf")
{
//string completePath = Path.Combine(Server.MapPath("~"), folderName);
//string PdfFile = completePath + "/" + "PDF";
////if (!Directory.Exists(PdfFile))
//{
// Directory.CreateDirectory(PdfFile);
//}
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef.ToString());
byte[] arr = new byte[len];
fileInfo.Stream.Read(arr, 0, arr.Length);
return arr;
}
else
{
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef.ToString());
byte[] arr = new byte[len];
fileInfo.Stream.Read(arr, 0, arr.Length);
return arr;
}
}
What am I missing?
Probably it occurs since file size is determined incorrectly. Try to remove any dependency to file size from DownloadFile method as demonstrated below:
public static byte[] DownloadFile(ClientContext ctx,string fileUrl)
{
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl);
using (var ms = new MemoryStream())
{
fileInfo.Stream.CopyTo(ms);
return ms.ToArray();
}
}

Convert base64 to downloadable zip file in MVC c#

I have been able to download a zipfile before but then the compression happend on the ASP server. Now we have changed this action to another server (Progress).
At this moment I'm receiving a base64 encoded string which represents a zip file. But how can I convert this string to a zipfile. The code I used before you can find beneath, can I reuse code?
MemoryStream outputStream = new MemoryStream();
outputStream.Seek(0, SeekOrigin.Begin);
using (ZipFile zip = new ZipFile())
{
foreach (string id in idArray)
{
string json = rest.getDocumentInvoice(Convert.ToInt32(id));
byte[] file = json.convertJsonToFile();
zip.AddEntry("invoice" + id + ".pdf", file);
}
zip.Save(outputStream);
}
outputStream.WriteTo(Response.OutputStream);
Response.AppendHeader("content-disposition", "attachment; filename=invoices.zip");
Response.ContentType = "application/zip";
return new FileStreamResult(outputStream, "application/zip");
I have no idea how to convert a string to a zip file. Thanks in advance for your help
Convert the base64 to a byte array by doing:
Convert.fromBase64String(strBase64);
Then I found an article to easily download the zipfile
Download file of any type in Asp.Net MVC using FileResult?
This article suggests:
public FileResult Download()
{
string base64 = getBase64ZIP();
byte[] byteArray = Convert.fromBase64String(base64);
return File(byteArray, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Use Convert.FromBase64String to get the bytes of the zip file.
string base64String = rest.getDocumentInvoice(Convert.ToInt32(id));
byte[] file = Convert.FromBase64String(base64String);
using(var stream = new MemoryStream(file))
{
zip.AddEntry("invoice" + id + ".pdf", stream);
}
Try this:
HTML:
> <a id='dwnldLnk' download='myzip.zip' style="display:none;" />
> <a ng-click="saveFile()">myzip.zip</a>
Controller:
var dataBase64 = "UEsDBAoAAAAAAORSo04AAAAAAAAAAAAAAAAEABwAc3VtL1VUCQADG7TLXKu/y1x1eAsAAQToAwAABOgDAABQSwMEFAAAAAgAe3WTTkQjafoxAAAAMgAAAAoAHABzdW0vc3VtLmdvVVQJAAM6fLlcha3LXHV4CwABBOgDAAAE6AMAACtITM5OTE9VKC7N5eJKK81LVgguzS3WSNRJUsjMK9EEEdVcnEWpJaVFeQqJ2klctQBQSwMEFAAAAAgAtkqWTksgx3NnAgAAPgQAAAcAHABtYWluLmdvVVQJAAM4Jb1cha3LXHV4CwABBOgDAAAE6AMAAHVTX0/bMBB/Jp/i5KeUlWTjkYmHDKiIxtKJlCGEeHCTS2qR2JntECrEd99dmm6VJvJi2b77/TsnPg7gGG5UgdphCd6A3yAknSxoyU3lB2kRFqbXpfTKaAiTfDED2qIFoxGMhdZYZJTCaG/Vuvd01uwQQdYWsUXtXQSQI47w2XKVXlxBpRqEUrldE7EPym8YyG+Ug8HYZ6gISpalYmrZgNJ00O6EWKylLZWuibfbWlVvPJhBo3Ub1UUMs2In+WKvxe1wR1by+WD6ycaB4ymIOfwiHGY5jT4zVMg1YroVs6+wpe5WbkEbD73DA2h8LbDzJJV0tV2jpC7wwNlfDsrjYQIxay+pXo5OwFSHZSA9NXIvfxvvu7M4HoYhkqPiyNg63huMbyjWLL862anmpjvdoHMU1u9eWYp4vQXZkapCrklrIwce4DikcfikYrCUtq7n4KbpM8zhlP6FtpdI1g8LKDapQSQ5pLmAb0me5nMGuU9X18u7Fdwnt7dJtkqvcljewsUyu0xX6TKj3QKS7AG+p9nlHJAiIx587Sw7IJmK48RynO3+Ke0l8EPhveuwUJUqyJque1kj1OYFreZ30qFtleOxOhJYMkyjWuXH9+T+98VEcRBQzs8M1NKMgoBEGOshDI6E61tBS9V6Xsg//QAvIpgFQRzDD54oqRrk+EYp22tsGhNUvS7Gy1Da2hFo98jJ6fpJaY+2kgW+vc8+OIe34Ijoop904RsdCgYSs+CIIoKzc+p6xvADyLHoUdSGkzlhMyeTM/EE5yBGeXMQ8AkmK1HqjQzJZZT3rQu/zE9nI4rvLf9+Lnj/A1BLAQIeAwoAAAAAAORSo04AAAAAAAAAAAAAAAAEABgAAAAAAAAAEAD/QQAAAABzdW0vVVQFAAMbtMtcdXgLAAEE6AMAAAToAwAAUEsBAh4DFAAAAAgAe3WTTkQjafoxAAAAMgAAAAoAGAAAAAAAAQAAAP+BPgAAAHN1bS9zdW0uZ29VVAUAAzp8uVx1eAsAAQToAwAABOgDAABQSwECHgMUAAAACAC2SpZOSyDHc2cCAAA+BAAABwAYAAAAAAABAAAA/4GzAAAAbWFpbi5nb1VUBQADOCW9XHV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAwADAOcAAABbAwAAAAA="
var dataFile = 'data:application/zip;base64,' + dataBase64
var dlnk = document.getElementById('dwnldLnk');
dlnk.href = dataFile;
dlnk.click();

Opening a File in C# using FileStream

I am trying to open a Binary file that I plan on converting to hex but I am running into issues with reading the file via FileStream,
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName); // Returns the proper directory with which to refernce the file
richTextBox1.Text += dirName;
richTextBox1.Text += chosenFile;
FileStream InputBin = new FileStream(
directoryPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
}
I am receiving an error saying that the access to the path is denied, any ideas?
Now that I have gotten that error taken care of I have ran into another Issue, I can read the binary file, but I want to display it as a Hex file, I'm not sure what I am doing wrong but I'm not getting an output in HEX, it seems to be Int values...
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += data[printCount];
printCount++;
}
Your code is miscommented
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
is not the filename, it's the directory path. You want:
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
Addtionally, if I were to guess based on your intentions, you should update your full function to be:
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
richTextBox1.Text += chosenFile; //You may want to replace this with = unless you mean to append something that is already there.
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
}
}
To answer your second quesiton:
I am receiving an error saying that the access to the path is denied,
any ideas?
Now that I have gotten that error taken care of I have ran into
another Issue, I can read the binary file, but I want to display it as
a Hex file, I'm not sure what I am doing wrong but I'm not getting an
output in HEX, it seems to be Int values...
Modify to use string.Format:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += string.Format( "{0:X} ", data[printCount];
printCount++;
}
}
I've included an ideone example.

Categories

Resources