Pregunta

I have a folder created to get the files that users upload. However when i try to download the files, some extensions don't download.

I have this code to list all files that are in the folder, i can see all the files with no problem.

@foreach (string fullFilePath in Directory.GetFiles(Path.Combine(Server.MapPath("~/uploadedFiles"),"Ticket Id - "+@id)))
                {
                    <div class="linkFicheiros"><a href="@Href("~/uploadedFiles","Ticket Id - "+@id, Path.GetFileName(fullFilePath))">@Path.GetFileName(fullFilePath)</a></div>
                }

With this line

<a href="@Href("~/uploadedFiles","Ticket Id - "+@id, Path.GetFileName(fullFilePath))">@Path.GetFileName(fullFilePath)</a>

i can download files with extension: ".zip" , ".xls" but extensions like ".msg"(sometimes users need to upload this extension) i got an error "The page cannot be found". Even ".jpg" instead of downloading the file it opens the image on the browser.

I think that is something how i'm trying to reach the file, but i can't get to a solution.

Any thoughts ?

¿Fue útil?

Solución

The browser would try to always view the content of the file. If its an Image file like .jng etc. But if there is a .zip file, it would let the user download and open it. Because browser can't open it.

You need to push the file to the user. For that you can try the following code:

var file = Server.MapPath("~/images/" + Request["img"]);
Response.AppendHeader(
"content-disposition", "attachment; filename=" + 
Request["img"]);
Response.ContentType = "application/octet-stream";
Response.TransmitFile(file);

Now, you can see that in the code I am sharing, the file is a variable, which is being pointed to the file in the File System. Please note that there is a Query String parameter, which would be sent alongwith the URL, for example:

Download Image

Now the header would be appened, and the

Request.ContentType = "application/octet-stream"

is used to force the browser to show the Dialoug of Open/Save.

Then the transmit file to download it.

To only execute the code when needed

To only execute that download code block, you need to set the value in a block for condition to be true. For example, you can use a parameter to check whether to download the file or not. Try something simple like,

<a href="~/download_file/image_link.png?download=true>Download</a>

Then on the code behind use this:

var download = Request.QueryString["download"];
if(download == "true") {
  /* place the code here */
}

Now it would only execute if the condition is true, otherwise it would skip that part.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top