I'm working on an ASP.NET MVC site where users are supposed to be able to upload images and PDF documents and view them at a later point. I noticed that certain filenames cause the attachments not to show.
I'm using Dropzone.js to provide a drag and drop field. The files are saved by a controller method using HttpPostedFileBase
. When a user opens the gallery view, the respective controller method lists all previously uploaded files (filenames) in a ViewBag entry. The view then creates a thumbnail for each image:
foreach (var path in (IEnumerable<string>)ViewBag.Attachments){
...
<img class="attachments-thumbnail" style="cursor: pointer" src="@Url.Content(path)" alt="" />
...
}
Now when I upload an image with the filename h &.jpg
, the thumbnail isn't shown. In Firefox, the console shows the error X GET http://localhost:54305/Content/Images/Attachments/1/h%20&.jpg
. So it's looking for h%20&.jpg
instead of h &.jpg
, even though the file was saved to the server as intended as h &.jpg
.
On the other hand, when I upload a pdf with the name radio%2E11%2E3%2E1852937.pdf
, this again gets saved with its original filename, but this time the error appears the other way around: X GET XHR http://localhost:54305/Content/Images/Attachments/1/radio.11.3.1852937.pdf
.
I'm not sure where this happens. When I use the inspector tool, the thumbnail <img>
tag points to the correct filename, i.e. the one present on the server. I imagine this must be a very frequent use case, so is there any C# method that makes a filename safe for web use or will I have to rename the files myself? Ideally of course I'd like to keep at least the filenames of the pdfs the way the user chose them, as they may indicate file content, but it seems to be unsafe..