FileContentResult and international characters in the file name - asp.net-mvc

I am using this code to return the file to the client
return new FileContentResult(Encoding.UTF8.GetBytes(sb.ToString()), MimeType)
{
FileDownloadName = String.Format("{0}.csv", fileName)
};
it works file when the file name is in ascii format, but it will return the name of the Action when the file name contains international chars
For example if filename is Report 新しいレポート the downloaded file is the name of the Action without any extension.
Update
This will happen in Chrome and ie, in Firefox the file is downloaded but some chars are changed
Firefox: Report2%0d%0a ��しいレポート_2016-03-09_09-20-35.c%0d%0a sv

For whom who have the same problem:
var browser = System.Web.HttpContext.Current.Request.Browser.Browser;
if (browser == "Chrome" || browser == "IE" || browser == "InternetExplorer")
{
fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
}
return new FileContentResult(Encoding.UTF8.GetBytes(sb.ToString()), MimeType)
{
FileDownloadName = String.Format("{0}.csv", fileName)
};

Related

Want exact file format on download which we had upload for signature on document sign

I am following these steps.
I am uploading the files of TEXT / PNG / DOCX / PPTX for the DocuSign using
c# API.
when I download that file after the signature of the document I got PDF format of that signature document except for uploaded file format.
Is there any alternate way of code or API how I got the same extension file on the download after signature done.
Envelope ID:- 3a6b752a-92f1-4751-b06a-ffb2c236f65d , 93409bdc-edcf-4e4b-8c6f-3c76c6305dcf , 5a32979b-3739-4585-a554-b725e1d65504
I am using below code in asp.net.
// get Lists the envelope documents.
public static EnvelopeDocumentsResult ListEnvelopeDocuments(string accountId, string envelopeId)
{
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeDocumentsResult docsList = envelopesApi.ListDocuments(accountId,
envelopeId);
return docsList;
}
// download file using envelopeId and that I get .pdf format
public static string DownloadSignedDocument(string envelopeId, string tempFileName, string companyCode, string apiUserName, string apiPassword, string integratorkey, string restApi)
{
ApiClient apiClient = new ApiClient(restApi);
Configuration.Default.ApiClient = apiClient;
// call the Login() API which sets the user's baseUrl and returns their accountId
string accountId = LoginApi(apiUserName, apiPassword, integratorkey);
// pass accountid and envelop id to get perticuler document for the download
EnvelopeDocumentsResult documentList = ListEnvelopeDocuments(accountId,
envelopeId);
string SignedPDFPath = string.Empty;
EnvelopesApi envelopesApi = new EnvelopesApi();
foreach (EnvelopeDocument document in documentList.EnvelopeDocuments)
{
MemoryStream docStream =
(MemoryStream)envelopesApi.GetDocument(accountId,
envelopeId, documentList.EnvelopeDocuments[0].DocumentId);
string documentName = document.Name != "Summary" ? document.Name :
"Summary";
SignedPDFPath =
systemConfiguration.ConfigurationManager.AppSettings["uploadFolder"] +
"/" + companyCode + "/" + "DocuSign/" + envelopeId;
if (!Directory.Exists(SignedPDFPath))
{
Directory.CreateDirectory(SignedPDFPath);
}
string[] tempFileExtention = tempFileName.Split('.');
string[] removeFileExtention = documentName.Split('.');
// need to give hardcoded ".pdf" extention because **document.Name**
//gives pdf file formate
SignedPDFPath = SignedPDFPath + "/" + removeFileExtention[0] + ".pdf"
;
// Server.MapPath("~/Uploadfiles/" + recipient.EnvelopeID + "/" +
// recipient.EnvelopeID + "_" + documentName + ".pdf");
using (FileStream fileStream = File.Create(SignedPDFPath))
{
docStream.Seek(0, SeekOrigin.Begin);
docStream.CopyTo(fileStream);
}
break;
}
return SignedPDFPath;
}
No.
All files are converted to PDF upon upload to DocuSign. If desired, you could use external tools to convert that PDF into another file format, but you would be breaking the 'tamper evident' digital seal on the document.

How to force excel file to open in browser instead of download?

I am working with MVC5 Crystal reports of pdf and excel files, my code works well for pdf to view in the web browser but when i change content-type to excel file its download only,
public ActionResult Summary(string startDate, string endDate, string summaryBy, string reportType)
{
using (MMTModel entity = new MMTModel())
{
string CryRpt_Name = null;
ObjectResult<DeeqtoonSummary> ObjRsl = null;
if (reportType == "Summary")
{
CryRpt_Name = "Summary.rpt";
ObjRsl = entity.rpt_Summary(startDate, endDate, summaryBy);
}
else if (reportType == "Detail")
{
CryRpt_Name = "Detail.rpt";
ObjRsl = entity.rpt_Detail(startDate, endDate);
}
ReportDocument rpt = new ReportDocument();
rpt.Load(Path.Combine(rpt.FileName = Server.MapPath("~/CrystalReports"), CryRpt_Name));
List<Summary> ObjRslLst = ObjRsl.ToList();
rpt.SetDataSource(ObjRslLst);
try
{
//Excel file
Stream stream = rpt.ExportToStream(ExportFormatType.Excel);
return File(stream, "application/vnd.ms-excel");
//pdf file
Stream stream = rpt.ExportToStream(ExportFormatType.PortableDocFormat);
return File(stream, "application/pdf");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
How can i force to open the excel file in the web browser?
I don't know anything about crystal-reports, but if your browser doesn't have an implementation for viewing excel documents then it will just download them. I have never been able to open an excel document with my browser unless the web application itself implements the display of the document.
Basically, you have to implement the MVC that displays an excel document yourself. Your browser doesn't support it out of the box.

How to convert MS-WORD file into HTML in ASP.NET MVC?

I am doing a project in which i have to to read a word document and perform some operation on file content. I have read the file successfully using
Open XML, but that's not enough. It read the file but does not retain the format and indentation. So the solution i found is that first read the file and convert it into HTML. Another thing i want all file content in "String" because i have to perform further operation on file contents.
So is there any way to read the MS-WORD file and convert into HTML and store in "string"?
Here i am showing the code of reading MS-WORD file.
[HttpPost]
public ActionResult OpenFile(HttpPostedFileBase file)
{
Rules R = new Rules();
string FileText = "";
if (file != null && file.ContentLength > 0)
{
string filename = Path.GetFileName(file.FileName);
R.name = filename;
string path = Path.Combine(Server.MapPath("~/Uploads"), filename);
file.SaveAs(path);
string filepath = path;
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filepath, true))
{
Body body = wordDoc.MainDocumentPart.Document.Body;
foreach (var paragraph in body.Elements<Paragraph>())
{
FileText += " <br> ";
}
}
R.Content += FileText;
}
return View(R);
}

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.

Mobile web application: download attachments on iOS

In my mobile web application i have one page within user can view attachments.
The attachment can be any type of file (jpg,png,txt,doc,zip, etc).
The view attachment action is in the form of <a> tag that points to an aspx file that process the request.
HTML:
<a class="attachBtn" href="_layouts/ViewFile.aspx?messageAttachmentInstanceId={some id}"></a>
ViewFile.aspx:
public partial class ViewFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.IO.BinaryWriter bw = null;
System.IO.MemoryStream ms = null;
System.IO.StreamReader sr = null;
try
{
string contentType = string.Empty;
byte[] content = null;
string fileName = string.Empty;
if (!string.IsNullOrEmpty(Request.QueryString["messageAttachmentInstanceId"]) &&
!string.IsNullOrEmpty(Request.QueryString["messageInstanceId"]))
{
int messageInstanceId = Int32.Parse(Request.QueryString["messageInstanceId"]);
Guid attachmentInstanceId;
GuidUtil.TryParse(Request.QueryString["messageAttachmentInstanceId"], out attachmentInstanceId);
MessageInstance messageInstance = WorkflowEngineHttpModule.Engine.GetService<IMessagingService>()
.GetMessageInstance(messageInstanceId);
if (messageInstance != null)
{
MessageAttachmentInstance attachmentInstnace = messageInstance.Attachments[attachmentInstanceId];
contentType = attachmentInstnace.ContentType;
fileName = attachmentInstnace.FileName;
content = attachmentInstnace.Content;
}
}
this.Response.ContentType = contentType;
string headerValue = string.Format("attachment;filename={0}",
this.Server.UrlPathEncode(fileName));
Response.AddHeader("content-disposition", headerValue);
bw = new System.IO.BinaryWriter(this.Response.OutputStream);
bw.Write(content);
}
catch (Exception ex)
{
LogError("ViewFile.aspx, "
+ ex.InnerException, ex);
}
finally
{
if (sr != null)
sr.Close();
if (ms != null)
ms.Close();
if (bw != null)
bw.Close();
}
}
}
The Problem:
in Android devices when user click on attachment the file is downloaded automatically which is the desirable behavior because the user can open the file later with any tool he wants and even if the file type is not supported user can later on download a tool which can open it.
but in iOS devices the file is not downloaded but instead redirects to ViewFile.aspx and tries to open the file within the browser and if the file type is not supported it shows alert: "safari cannot download this file".
even if the file type is supported i want it to be downloaded and not open by default.
How can i achieve this behavior?
AFAIK, you cannot download files on iOS.
Known files that Safari (or any app that has registered a file type, e.g. ZIP) supports will open or show a dialog letting the user choose how to open the file.
You can't control the behavior from your web app/site.

Resources