I have Base64 string that represents a PDF file which needs to be converted to a PDF file, and open with the default PDF reader or browser in C#.
I have written only the part of Base64 string because it's too long string to paste here.
public void DownloadPDF()
{
string pdflocation = "E:\\";
string fileName = "softcore.pdf";
// This is only part of Base64 string
var base64String = "JVBERi0xLjQKJdP0zOEKMSAwIue704O58dOXPgst+hmQ+laj/";
int mod4 = base64String.Length % 4;
if (mod4 > 0)
{
base64String += new string('=', 4 - mod4);
}
byte[] data = Convert.FromBase64String(base64String);
if (Directory.Exists(pdflocation))
{
pdflocation = pdflocation + fileName;
using (MemoryStream Writer = new System.IO.MemoryStream())
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.AddHeader("content-length", data.Length.ToString());
Writer.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
//Writer.Write(data, 0, data.Length);
}
}
}
The problem I'm facing is that it shows as pdf generating but at the end, it says Network error.
The decoded string from the input encoded Base64 string:
This code works fine if a PDF is converted base 64 from some online platform like freeformatter.com/base64-encoder.html and use that base 64 string in the code below:
string pdflocation = "D:\\";
string fileName = "softcore.pdf";
// put your base64 string converted from online platform here instead of V
var base64String = V;
int mod4 = base64String.Length % 4;
// as of my research this mod4 will be greater than 0 if the base 64 string is corrupted
if (mod4 > 0)
{
base64String += new string('=', 4 - mod4);
}
pdflocation = pdflocation + fileName;
byte[] data = Convert.FromBase64String(base64String);
using (FileStream stream = System.IO.File.Create(pdflocation))
{
stream.Write(data, 0, data.Length);
}
This should save the PDF file in D:\\ , again the problem is in your base 64 encoded string
Hope this helps.
Related
I am trying to create an API which will save an image at a given location .
Below is my Code for that
Image image = Image.FromFile(#"C:\Users\abc\Desktop\img-logo.jpg");
byte[] bytes = (byte[])(new ImageConverter()).ConvertTo(image, typeof(byte[]));
string str = Convert.ToBase64String(bytes);
Save_Application_Image("12004", str);
and the method in API
public void Save_Application_Image(string staffCode , string bytearray)
{
try
{
byte[] bytes = Convert.FromBase64String(bytearray);
file_path = "~/uploads/" + file_name;
FileStream file = File.Create(HttpContext.Current.Server.MapPath(file_path));
file.Write(bytes, 0, bytes.Length);
file.Close();
}
catch(Exception ex)
{
logger.LogError(ex);
}
finally
{
}
}
This api has to be called from Android Application so I will receive two string parameter.
It is saving the file perfectly but file is not readable. No preview for image file.
What is the right approach for this ?
I'm unsure of how the ImageConverter works, but I've used this before to convert Images to byte[]:
Image image = Image.FromFile(#"C:\Users\abc\Desktop\img-logo.jpg");
using (var stream = new MemoryStream())
{
image.Save(stream);
string savedImage = Convert.ToBase64String(stream.ToArray());
Save_Application_Image("12004", str);
}
I am trying to download a file over a RESTful Webservice and then save the file on the computer.
I am using an PDF-File to test the code. I found out the data is UTF-8 encoded so i tried encoding it back to default, because i found out by reading the pdf file locally and writing it back again that it works that way.
Here is my code:
IConsumerRequest getDocumentRequest = class.consumerSession
.Request()
.ForMethod("GET")
.ForUri(new Uri(class.apiEndpoint + "/1/documents/" + id))
.SignWithToken(class.accessToken);
string test = System.IO.File.ReadAllText("C:\\test.pdf", Encoding.Default);
byte[] bytes = Encoding.UTF8.GetBytes(getDocumentRequest.ToString());
string data = Encoding.Default.GetString(bytes);
MessageBox.Show(test.Substring(0, 120) + "\n\n" + data.Substring(0, 120));
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllBytes(saveFileDialog.FileName, bytes);
}
Comparing the string shows the following (second line):
Local String vs String from Webservice
I already tried several ways to convert the string without any difference.
You can use the Encoding.Convert method.
byte[] converted = Encoding.Convert(Encoding.UTF8, Encoding.Default, bytes);
Got it to work with HttpWebResponse:
HttpWebResponse webResponse = getDocumentRequest.ToWebResponse();
Stream stream = webResponse.GetResponseStream();
Encoding enc = System.Text.Encoding.GetEncoding(UTF8);
StreamReader loResponseStream = new StreamReader(webResponse.GetResponseStream(), enc);
string serverResponse = loResponseStream.ReadToEnd();
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllText(saveFileDialog.FileName, serverResponse, Encoding.Default);
}
I'm trying to convert a stream to image using C#, but the image is appearing corrupt.
Here is how i'm getting the BaseString representation
byte[] imageArray = System.IO.File.ReadAllBytes(#"C:\Users\jay.raj\Desktop\images\images\tiger.jpg");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
Now I'm passing this to a function which converts it into Stream and tries to convert it into image file.
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
MemoryStream stream = new MemoryStream(byteArray);
UtilityHelper.UploadImageFormDevice(stream, ref ss);
Here is the UploadImageFormDevice function:
public static ResponseBase UploadImageFormDevice(Stream image, ref string imageName)
{
ResponseBase rep = new ResponseBase();
try
{
string filname = imageName;
string filePath = #"C:\Users\jay.raj\Desktop\Upload\";
if (filname == string.Empty)
filname = Guid.NewGuid().ToString() + ".jpg";
filePath = filePath + "\\" + filname;
FileStream fileStream = null;
using (fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 1024;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = image.Read(buffer, 0, bufferLen)) > 0)
{
fileStream.Write(buffer, 0, count);
}
fileStream.Close();
image.Close();
}
imageName = filname;
}
catch (Exception ex)
{
rep.Code = 1000;
rep.Message = "Server Error";
}
return rep;
}
As #naivists wrote try replace this line:
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
To this line:
byte[] byteArray = Convert.FromBase64String(mySettingInfo.FileToUpload);
It looks like you want to transfer a file from #"C:\Users\jay.raj\Desktop\images\images\tiger.jpg" to #"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg".
In your case you read the file as a byte array, convert it into a base 64 coded string and then again into a byte array. This is unnecessary and error prone. In your case you missed the decoding.
If you ignore for a moment that it is an image and see it just as a bunch of bytes things might get easier.
string srcPath = #"C:\Users\jay.raj\Desktop\images\images\tiger.jpg";
string dstPath = #"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg";
byte[] imageArray = System.IO.File.ReadAllBytes(srcPath);
System.IO.File.WriteAllBytes(dstPath, imageArray);
I have been working with epplus on .NET desktop projects (C#) and using templates like this:
var package = new ExcelPackage(new FileInfo("C:\\Templates\\FormatoReporteSamsung.xlsx"))
But now I'working with a .NET Web Project (C#) and i don't know what make to refer to the template that exist like a web resource where the URI of that resource like this:
http://myownweb:29200/Content/excelTemplates/Formato.xlsx
At the end I pass the excel template as a stream using this code.
using (var package = new ExcelPackage(new MemoryStream(GetBytesTemplate(FullyQualifiedApplicationPath + "Content/excelTemplates/Format.xlsx"))))
{
//Write data to excel
//Read file like byte array to return a response
Response.Clear();
Response.ContentType = "application/xlsx";
Response.AddHeader("content-disposition", "attachment; filename=" + "myFileName" + ".xlsx");
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
To read the excel file has bytes I use this
Error "This stream does not support seek operations" in C#
private byte[] GetBytesTemplate(string url)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();
byte[] b = null;
using (Stream stream = myResp.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
b = ms.ToArray();
}
return b;
}
And to get the name of the website i use
http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/
public string FullyQualifiedApplicationPath
{
get
{
//Return variable declaration
string appPath = null;
//Getting the current context of HTTP request
HttpContext context = HttpContext.Current;
//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
context.Request.Url.Port == 80
? string.Empty : ":" + context.Request.Url.Port,
context.Request.ApplicationPath);
}
if (!appPath.EndsWith("/"))
appPath += "/";
return appPath;
}
}
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/y1x1eAsAAQToAwAABOgDAABQSwMEFAAAAAgAe3WTTkQjafoxAAAAMgAAAAoAHABzdW0vc3VtLmdvVVQJAAM6fLlcha3LXHV4CwABBOgDAAAE6AMAACtITM5OTE9VKC7N5eJK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oxAAAAMgAAAAoAGAAAAAAAAQAAAP+BPgAAAHN1bS9zdW0uZ29VVAUAAzp8uVx1eAsAAQToAwAABOgDAABQSwECHgMUAAAACAC2SpZOSyDHc2cCAAA+BAAABwAYAAAAAAABAAAA/4GzAAAAbWFpbi5nb1VUBQADOCW9XHV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAwADAOcAAABbAwAAAAA="
var dataFile = 'data:application/zip;base64,' + dataBase64
var dlnk = document.getElementById('dwnldLnk');
dlnk.href = dataFile;
dlnk.click();