I've got a rather odd situation happening, that I'm having difficulty tracking down in an existing Django application. One of the views, which inherits from APIView, returns with a file when a user makes a POST call. The endpoint works fine, but there's something odd happening when the downloaded file reaches the client machine. By the time the browser receives the file, the file extension has been renamed with a trailing underscore. (So suppose the file was originally "test.txt", the version that the client receives would be "test.txt_").
As near as I can figure, just before the response object is returned in the APIView, the content-type and content-disposition headers look correct. E.g.:
Content-Type: application/octet-stream
Content-Disposition: attachment;filename="test.txt"
That same file, when it shows up in Chrome downloads, is named "test.txt_" - with the trailing underscore. I've tried the same thing out in Firefox, and it seems to download correctly. Unfortunately, telling the majority of our users to switch browsers isn't going to fly.
I have tried:
Forcing a different content type (e.g.: instead of "application/octet-stream", try "application/text", just to see what happens). This had no effect.
Formatting the content disposition slightly different (e.g.: space between the semicolon and filename). This also had no effect.
Removed the double quotes around the filename in the content-disposition header. No effect.
Dropping breakpoints within the Rest Framework itself, but Visual Studio Code doesn't seem to trigger on these. (I'm not super-familiar with debugging through Visual Studio Code, so this may be my fault).
Stripped out any custom middleware, so the only remaining middleware are as follows:
corsheaders.middleware.CorsMiddleware
django.contrib.sessions.middleware.SessionMiddleware
django.middleware.locale.LocaleMiddleware
django.middleware.common.CommonMiddleware
django.middleware.csrf.CsrfViewMiddleware
django.contrib.auth.middleware.AuthenticationMiddleware
django.contrib.messages.middleware.MessageMiddleware
So far, any similar issues that other people have experienced seem to be slightly different (i.e.: Internet Explorer removing the period in the extension and replacing it with an underscore).
Any guesses on what might be happening here? I'm a bit stumped.
You have to remove "" from your file name
Change attachment; filename="filename.txt" to attachment; filename=filename.txt
Although seems like you won't be able to have spacing in file name
I finally figured out what was going on here. The UI that was used to trigger the download was doing so through creating a temporary anchor tag (see the second answer here: Download data url file ). When it was doing so, it had two different cases. In one case, if downloading multiple files, it would change the file extension to .zip. In another case, if downloading a single file, it was still trying to append an extension, but the way the UI code was written, it was setting the extension to be an empty string. So the end result is a period being added, but no extension after that. For example, if the file being downloaded was "test.txt", it would end up as "test.txt.", which was then converted by Chrome to "test.txt_", on Windows, to make it a valid file extension.
Our environment has a document storage system that contains documents with the attributes DocumentName and ContentType. In some cases, the content type would return with spaces appended to the end of the string like "pdf ".
In Internet Explorer the output would truncate the end of the string while Chrome would convert the extra spaces to underscores giving me this filename: "file.pdf______________"
To resolve I simply truncate the string.
public string getFileName(string docName, string contentType) {
string fileName = docName + "." + contentType.Trim();
return fileName;
}
I encountered the same problem.
Let's say your download file name is "my_report.csv"
Then before doing the download operations get rid of " characters
fileName = fileName.replace('"','') // replacing one " charcter
fileName = fileName.replace('"','') // replacing second " character
This will resolve your issue.
My solution in ASP.NET core
[HttpGet("pdf/{fileId}")]
public IActionResult GetPdfFile([FromRoute]int fileId)
{
var result = Repo.GetFile(fileId);
Response.Headers.Add("Content-Disposition", $"inline; filename={result.FileName}");
return File(result.Data, "application/pdf");
}
I resolved this issue with replace white space in file name by a character like -.
This was happening for me when the filename included a comma.
lastname,MD.pdf
browser would download filestream as
_lastname,MD.pdf_
Adding code to remove a potential comma from the filename resolved the issue and made it download as expected.
filename = filename.Replace(",", ""); // replace comma characters with blank
now downloads as
lastnameMD.pdf
In my case there was a space as a first character, and it was replaced to underscore. So I simply removed the space :-)
Related
While moving a website - that I did not build - I have run into the use of %3F.
%3F is the percent-encoded version of ?.
It seems to be used like this a lot:
Example
when linking to a file named example_lang=1.html.
So, I replaced %3F with _, and all works again.
I am missing something here. The old website worked. After being moved, it no longer worked. After the replacement of %3F to _, the links worked again. Why?
First, you should elaborate your question to understand it better after all If I understood it correctly then this might be the answer.
"_" is not a reserved URI character.
As you said that %3F is reserved for "?" then you are absolutely right but if you read the documentation written on wiki states that "_"(underscore) is not a reserved URI character.
So that for example if the URL for a web page is "example_test.html" then its encoded URL must be "example_test.html" if there is not any mechanism applied on that URL. Now I will take an another example of PHP based web page that may answer your question.
In PHP there is a function "str_replace" that is used to replace the string by programmer defined characters or string.
Let assume that I have a page named "example_test.html" and for some xyz reasons I want to change it to "example%3Ftest.html" then I can use
str_replace("%3F","_","<a href='example%3Ftest.html'>Example Test</a>");
This function will search for all occurences of "%3F" and replace it with "_" in provided string(here "href=example%3Ftest.html") and output as "href='example_test.html" which is the actual link for my file.
This seems like it ought to be a trivial question, but I'm having a hell of a time finding an answer for this so far...
I have an access database that stores hyperlinks to files on a shared network drive. The link targets are specified as simple file paths (e.g. "G:\directoryname\filename.ext") rather than proper URL's ("http://domain.ext/link").
This works fine in general, but I've recently run into a problem involving file names that contain the "#" character. (It is not an option to change the file names to remove the # characters)
If I try to set up a link to something like "G:\directoryname\ExampleFile#24.pdf", then Access parses the # in the filename as it would generally do when it defines a hyperlink. The resulting target is just ""G:\directoryname\ExampleFile", with the portion of the link following the offending "#" simply being truncated.
Now, obviously if the link target were a regular URL, I would just replace the "#" in the text of the link with "%23" and there would be no issue.
The problem is that, if I do that here, my network file action fails, because unlike when opening a regular URL through a browser, the network doesn't recognize %23 as equivalent to # ( I get an error saying "Unable to open G:\directoryname\ExampleFile %23 24.pdf. Cannot open the specified file.")
Is there a more direct way to have ms-access record the link target with a literal # character included?
Well this certainly doesn't help you but here is your answer:
"You cannot use a pound character in a file name for a hyperlink in an Office program"
https://support.microsoft.com/en-us/kb/202261
I added this HTML to a page that I render via a REST call:
StringBuilder builder = new StringBuilder();
. . .
builder.Append("<p></p>");
builder.Append("<a href=\"/App_Data/MinimalSpreadsheetLight.xlsx\" download>");
builder.Append("<p></p>");
. . .
return builder.ToString();
My ASP.NET Web API project has a folder named "App_Data" which does contain a file named "MinimalSpreadsheetLight.xlsx"
The download link is indeed rendered on the page, and clicking it does appear, at first, to download the file (it has the Excel icon, and it bears the file name), but beneath that it says "Failed - No file":
Is the problem with my HTML, or the path I'm using, or file permissions, or what?
I've only tested this with Chrome, so far, BTW. IOW, it's not an IE issue.
UPDATE
I tried it with a leading squiggly, too:
builder.Append("<a href=\"~/App_Data/MinimalSpreadsheetLight.xlsx\" download=\"Spreadsheet file\">");
...yet, alas, to no avail.
UPDATE 2
I changed the pertinent line of HTML to this:
builder.Append("<a href=\"App_Data/MinimalSpreadsheetLight.xlsx\" download=\"Minimal Spreadsheet file\">");
...and it displays in the source like so (with some context):
<p>(Invoice Count excludes credits and re-delivery invoices)</p><p></p><p></p><a href="App_Data/MinimalSpreadsheetLight.xlsx" download="Minimal Spreadsheet file">
...but the link does not appear at all.
UPDATE 3
I was misled by this reference, which showed no text being added; I changed the code to this:
builder.Append("Spreadsheet file");
...(adding "Spreadsheet file" and closing out the anchor tag), and now the link appears; however, I still get the "Failed - No file" msg, and 2-clicking the "downloaded file" does nothing.
UPDATE 4
I tried two other permutations of what's seen in Update 3, namely with the forward whack reintroduced prior to "App_Data":
builder.Append("Spreadsheet file");
...and with both the squiggly prepended and the forward whack:
builder.Append("Spreadsheet file");
...but the results are the same in any of these permutations ("Failed - no file").
UPDATE 5
I also tried it without the "App_Data" at all, on the off change that is not needed:
builder.Append("Spreadsheet file");
...but the same "Failed - No file" is the result of that attempt, too.
UPDATE 6
Okay, so I tried this, too (single quotes):
builder.Append("<a href='/App_Data/MinimalSpreadsheetLight.xlsx' download='Minimal Spreadsheet file'>Spreadsheet file</a>");
...but no change. The file is there:
...so why is it not seen or accessible?
UPDATE 7
This:
string fullPath = HttpContext.Server.MapPath("~/App_Data/MinimalSpreadsheetLight.xlsx");
... (which I got from here) fails to compile with, "An object reference is required for the non-static field, method, or property 'System.Web.HttpContext.Server.get'
2-clicking the err msg highlights just "Server"
UPDATE 8
This (which I got from the same place as what I tried in Update 7):
string justDataDir = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
string url2 = string.Format("Spreadsheet file</button>", justDataDir);
builder.Append(url2);
...does nothing; clicking the link doesn't even give me a fake/failed download now...
justDataDir is:
C:\Projects\ProActWebReports\ProActWebReports\App_Data
url2 is:
Spreadsheet file</button>
UPDATE 9
I noticed on further fine-tooth-combing that url2 had a forward whack in it; I changed it so that all the whacks were back, but it made no difference to Update 8's results: clicking the link does nothing whatsoever.
If somebody solves this, it will definitely get bountified after the fact.
UPDATE 10
Maybe what I really need to do is, instead of the simple html, add some jQuery that will download the file. But the question is, can jQuery access the App_Data folder any better than raw/simple html can?
The app_data folder is used by iis and asp.net as a private area in which to put database files which can only be accessed by code running on the server.
If you try to access the folder directly via your browser you will get a permissions error.
In order to make the files available for download, move them the a folder under 'Content' (if you have an mvc site) and ensure that your web.config allows the .xlsx exention to be downloaded.
It may depend on what version of iis you are using.
Downloading Docx from IE - Setting MIME Types in IIS
I have a simple question. When I create a CommaIO, it works but when I arrive to the 'if' statement, it doesn't go to inside the 'if'. The message 'blabla' is never printed. Nevertheless, the file name is correct and the path also. My csv files was saved in Excel with csv(comma delimited) extension. The file and directory are authorized in read mode
commaIO = new CommaIO(#"C:\\Users\\lbagno\\Documents\\SalesPrice.csv","r");
print "blabla";
pause;
print "fdf";
pause;
if(commaIO)
{
print "ici3";
pause;
}
Where is the problem ?
Thank you
When I first saw this I thought it was because you had \\ aswell as the # but seemingly in my code it works when I put it in a job.
Few questions.
try removing the \\ so it is just \ and see whether that fixes it (as I said it doesnt make a difference on mine)
Does the user running AX have access to that file path?
Does the file exist.
A few pointers for you, try using info("string") instead of print and pause, it's more standard and you dont have to pause every step.
Also commaIO has been superceeded by CommaTextIo. Looks like you can use the same code but I'm guessing it adds some functionality. http://msdn.microsoft.com/en-us/library/aa624902(v=ax.50).aspx
I can't comment on this post because of I don't have a high enough reputation so sorry if this isn't helpful as an answer.
Try moving the file to C:\Temp directory. It may be a permissions issue!!
The # makes it a string literal...so you're doing double \\ for no reason...but I think it still does work.
Use one of the two though:
CommaIo commaIO = new CommaIO(#"C:\Users\lbagno\Documents\SalesPrice.csv","r");
CommaIo commaIO = new CommaIO("C:\\Users\\lbagno\\Documents\\SalesPrice.csv","r");
Also, checking if (commaIo) will work if it finds a valid file, then you run while (commaIo.status() == IO_Status::Ok).
I'd say the issue is that either your file does not exist (as typed), it's a client/server issue, OR it's a permissions issue.
Start with a job and a local file.
I am having a similar problem to MicrosoftOfficeEditDocument didn't work in Chrome.
I did download the updated library as said in the answer and it works fine with Office 2013 but not with 2010.
With Office 2010, I have some files that open and some that don't, they are not always the same ones. I tried with .doc, .docx, .ppt, .pptx, .xls and .xlsx.
I call the edit document fonction with :
ITHit.WebDAV.Client.DocManager.EditDocument(sDocumentUrl, javaAppletFilePath);
EDIT :
It actually seems to be a problem of length of file url. When my file url (sDocumentUrl) is longer than the length of my script url in which I call EditDocument it works perfectly fine. But when it is shorter, the end of the script url is added after sDocumentUrl which makes the call fail. And this only happens with Chrome and Office 2010.
Any way to make this work ?
Add '\0' to the end of the URL
Add a '\0' (null) to the end of the string you are passing to MicrosoftOfficeEditDocument(). Like MicrosoftOfficeEditDocument(path + '\0');. Also, you should use MicrosoftOfficeEditDocument() instead of EditDocument() because EditDocument() will try to call JavaEditDocument() because of the null terminated string.
This is a solution taken from here - https://code.google.com/p/chromium/issues/detail?id=269183#c5
For more info - opening webdav files in Chrome via the Office Authorization plug-in for NPAPI browsers fails for certain files
Check for ActiveX first
However, you should not add the '\0' to the path when MicrosoftOfficeEditDocument() will open the document via the SharePoint.OpenDocument ActiveX object or else the ActiveX plugin will not recognize the file format via extension and try to open the document via undefined:ofe|u| instead of ms-word:ofe|u| for example. To do this you should check for ActiveX before appending the '\0'.
if (!('ActiveXObject' in window)) {
path = path + '\0';
}
ITHit.WebDAV.Client.DocManager.MicrosoftOfficeEditDocument(path)
Warning: this solution breaks MicrosoftOfficeEditDocument in Firefox. Firefox does not like the \0 terminated string.