Unable to open blob url in IE with print dialog - asp.net-mvc

I'm trying to open a PDF file with print dialog in IE Edge, it works fine in chrome but not in IE
MVC code to return file using Evo Pdf tool:
var restClient = new RestClient(Request.Url.Scheme + "://" + Request.Url.Authority);
var restResponse = restClient.Execute(request);
if (restResponse.StatusCode == HttpStatusCode.OK)
{
htmlModel.HtmlString = restResponse.Content;
byte[] pdfBytes = PdfUtil.GetEvoPdfBytes(htmlModel);
if (pdfBytes != null)
{
return File(pdfBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, htmlModel.PdfName + ".pdf");
}
}
Javascript code to open file with print dialog, below code works in chrome but not IE:
var req = new XMLHttpRequest();
req.open("POST", "/api/HtmlToPdf", true);
req.setRequestHeader("Content-Type", "application/json");
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var lin = window.URL.createObjectURL(blob);
// Works in chrome
var mywindow = window.open(lin, "_blank");
mywindow.focus();
mywindow.print();
};
req.send(JSON.stringify(
{
htmlModel: {
ElementSelector: "#div",
PageOrientation: "Portrait",
PdfName: "abc"
}
}));

IE11 does not support URL.createObjectURL(). So your code will not work for IE browser and you will not be able to open the blob with print dialog..
As a work around, you need to use msSaveBlob or msSaveOrOpenBlob for Internet Explorer browser.
These methods allow a user to save the file on the client as if the file had been downloaded from the Internet.
var blobObject = new Blob(["This is sample text..."]);
window.navigator.msSaveOrOpenBlob (blobObject, 'msSaveOrOpenBlob_testFile.txt');
References:
(1) Download a blob from HTTP URL in IE 11
(2) Saving files locally using Blob and msSaveBlob
(3) Blob download is not working in IE

Related

ionic capacitor app Failing to upload file using xhr

i am trying to upload image captured from camera using ionic and capacitor and below code i am using:
var url = 'https://api.cloudinary.com/v1_1/' + this.cloudName + '/image/upload';
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("Access-Control-Allow-Origin","*")
xhr.onreadystatechange = (e) => {
this.loading = false;
if (xhr.readyState == 4 && xhr.status == 200) {
// File uploaded successfully
var response = JSON.parse(xhr.responseText);
var url = response.secure_url;
// Create a thumbnail of the uploaded image, with 150px width
var tokens = url.split('/');
tokens.splice(-2, 0, 'w_150,c_scale');
var img = new Image(); // HTML5 Constructor
img.src = tokens.join('/');
img.alt = response.public_id;
document.body.appendChild(img);
//window.alert(url);
this.imageUrl = url;
this.capturedImage = this.base64Image;
//alert('capture:' + capturedImage);
}else{
console.log("unable to load image to the cloud" + xhr.readyState + ":" + xhr.status + ":" + xhr.responseText)
}
};
fd.append('upload_preset', this.unsignedUploadPreset);
fd.append('tags', emailid); // Optional - add tag for image admin in Cloudinary
fd.append('file', this.base64Image);
xhr.send(fd);
it prints: unable to load image to the cloud 4:0:
I'm a little confused by your code because it looks like you are trying to access the response before you've actually sent anything. I would recommend using one of the Cloudinary SDKs as it will make your life a lot easier.
https://cloudinary.com/documentation/image_upload_api_reference#upload_examples
Here is an example of another upload using Ionic and Capacitor.
https://devdactic.com/ionic-image-upload-capacitor

Pdf missing signature after uploading from ASP.NET MVC XMLHttpRequest

I'm working on a ASP.NET MVC page to let users upload a Pdf document once they have digitally signed it.
But for some reason the signature is destroyed when uploading the document even when it's graphic representation is properly displayed.
Here is the code I use to upload the file:
$(document).on('click', 'input[value=Upload]', function (e, argument) {
var formdata = new FormData();
for (i = 0; i < document.getElementById('FileBox').files.length; i++) {
formdata.append(document.getElementById('FileBox').files[i].name, document.getElementById('FileBox').files[i]);
}
var url = '#Url.Action("Upload", "Test")'
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = $.parseJSON(xhr.response);
alert(response.result);
}
}
});
I'm retrieving the uploaded files in the controller as follows:
Public Function PostedFiles() As List(Of Byte())
Dim retval As New List(Of Byte())
Dim oRequest As HttpRequest = Web.HttpContext.Current.Request
For Each sFileKey As String In oRequest.Files
Dim oFile As HttpPostedFile = oRequest.Files(sFileKey)
If oFile.ContentLength > 0 Then
Dim iLength As Integer = oFile.ContentLength
Dim oBytes(iLength) As Byte
Dim oStream As System.IO.Stream = oFile.InputStream()
oStream.Read(oBytes, 0, iLength)
retval.Add(oBytes)
End If
Next
Return retval
End Function
After persisting the byte arrays in a SQL server database, when I take them back from the database there is no longer any signature, just the graphic representation of it.
Thanks Mkl for your comment, I realize I was getting no signature since the document was displayed in the browser. Opening the persisted file in Acrobat Reader successfully shows the signature.

can eml directly open with outlook, instead eml file will download then click it to open in outlook?

I have an asp.net MVC application, below code works file.
But the code is that, When navigate to Email action in browser, an EML file is download, then when we click on that file, the file will open with outlook.
Can it be possible, when action calls, then EML file will directly open with outlook, instead of download and then click to open??
Code
public async Task<FileStreamResult> Email()
{
string dummyEmail = "test#localhost.com";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(dummyEmail);
mailMessage.To.Add("dejan.caric#gmail.com");
mailMessage.Subject = "Test subject";
mailMessage.Body = "Test body";
// mark as draft
mailMessage.Headers.Add("X-Unsent", "1");
// download image and save it as attachment
using (var httpClient = new HttpClient())
{
var imageStream = await httpClient.GetStreamAsync(new Uri("http://dcaric.com/favicon.ico"));
mailMessage.Attachments.Add(new Attachment(imageStream, "favicon.ico"));
}
var stream = new MemoryStream();
ToEmlStream(mailMessage, stream, dummyEmail);
stream.Position = 0;
return File(stream, "message/rfc822", "test_email.eml");
}
private void ToEmlStream(MailMessage msg, Stream str, string dummyEmail)
{
using (var client = new SmtpClient())
{
var id = Guid.NewGuid();
var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");
// create a temp folder to hold just this .eml file so that we can find it easily.
tempFolder = Path.Combine(tempFolder, id.ToString());
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = tempFolder;
client.Send(msg);
// tempFolder should contain 1 eml file
var filePath = Directory.GetFiles(tempFolder).Single();
// create new file and remove all lines that start with 'X-Sender:' or 'From:'
string newFile = Path.Combine(tempFolder, "modified.eml");
using (var sr = new StreamReader(filePath))
{
using (var sw = new StreamWriter(newFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("X-Sender:") &&
!line.StartsWith("From:") &&
// dummy email which is used if receiver address is empty
!line.StartsWith("X-Receiver: " + dummyEmail) &&
// dummy email which is used if receiver address is empty
!line.StartsWith("To: " + dummyEmail))
{
sw.WriteLine(line);
}
}
}
}
// stream out the contents
using (var fs = new FileStream(newFile, FileMode.Open))
{
fs.CopyTo(str);
}
}
}
With Chrome you can make it automatically open certain files, once they are downloaded.
.EML should attempt to open in Outlook.
I am not sure about other browsers, but Chrome seemed to be the only one with this option.
It's not a pefect solution because if someone downloaded an .EML from another website in Chrome, it will open automatically aswell.
I recommend having Chrome dedicated to your Web application.
You sure can open local .eml file with Outlook.
But in context of web application, you must firstly download it.

PCLStorage and binary data

I'm just new in this PCL libraries, I'm developing an iPhone app with Xamarin and I can't find the way to save it on the phone. The closest I get is with PCLStorage but he only saves text.
There is another way that I can save binary files with other procedure.
Thank you.
foreach (images element in json_object)
{
//var nameFile = Path.Combine (directoryname, element.name);
try{
IFile file = await folder_new.GetFileAsync(element.name);
}catch(FileNotFoundException ex ){
RestClient _Client = new RestClient(element.root);
RestRequest request_file = new RestRequest("/images/{FileName}");
request_file.AddParameter("FileName", element.name, ParameterType.UrlSegment);
_Client.ExecuteAsync<MemoryStream>(
request_file,
async Response =>
{
if (Response != null)
{
IFolder rootFolder_new = FileSystem.Current.LocalStorage;
IFile file_new = await rootFolder_new.CreateFileAsync(element.name,CreationCollisionOption.ReplaceExisting);
await file_new.WriteAllTextAsync(Response.Data);
}
});
}
}
Use the IFile.OpenAsync method to get a stream which you can use to read/write binary data. Here's how you would read a file:
IFile file = await folder_new.GetFileAsync(element.name);
using (Stream stream = await file.OpenAsync(FileAccess.Read))
{
// Read stream and process binary data from it...
}

Error in File downloading file from a folder in MVC2

I am encountering a problem in getting the download prompt. In the below code first am allowing the user to upload a file to compress. Once the file is compressed the user should be provided with the compressed files. But in the below code download prompt doesn't appears neither it shows any error. Please help me by correcting my code
The view code:
function CompressFile(box) {
var file = document.getElementById('fileComp');
if (file.value == "") {
alert("Choose a file to upload");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Compress', true);
xhr.send(fd);
}
The controller code:
public ActionResult Compress(HttpPostedFileBase file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file.FileName) ?? "";
if (file.ContentLength > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_uploadPDF), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
PdfReader reader = new PdfReader(filePath);
string name = DateTime.Now.ToString("ddMM_HHmmss");
name = Server.MapPath(_fileUploadPath + name + ".pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream(name, FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = true;
stamper.SetFullCompression();
stamper.Close();
string fn = System.IO.Path.GetFileName(name);
return base.File(name, "application/pdf",fn);
}
else
{
return View();
}
}
The problem is that you're using Ajax. You can't download a file through Ajax. You need to do a regular POST to the ActionMethod. That way the browser can send you back the file and prompt the user where he wants to save it.

Resources