简体   繁体   中英

Download File C#

So I can't believe I'm asking this question. This seems like it should be very straight forward. I have a photo album on a web site that basically shows the user 3 different buttons: Previous Image, Next Image and Download Current Image.

Everything is working fine with the exception of the Download Image button. All of my research points me back to using the WebClient method and it seems very straight forward. However, when I set this up, I constantly get the error of

System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Net.WebClient.DownloadFile(Uri address, String fileName) at System.Net.WebClient.DownloadFile(String address, String fileName) at mySite.Pictures.USMC.MarineCorpsGeneral.btnDownload_Click(Object sender, ImageClickEventArgs e) in C:\\Users\\myFile.aspx.cs:line 124 The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.FileIOPermission The Zone of the assembly that failed was: MyComputer

The error looks to be some kind of permissions issue but I've given god-like access to almost everyone and still no success. I have ready threads about adding the trust level to Full in the web config will do it but that did not work either. Here is my code:

protected void btnDownload_Click(object sender, ImageClickEventArgs e)
        {
            Response.Write("File Path: " + lblCenterImage.Text + "<br>");
            Response.Write("File Name: " + lblCenterImage.Text.Substring(lblCenterImage.Text.LastIndexOf("/") + 1, lblCenterImage.Text.Length - lblCenterImage.Text.LastIndexOf("/") - 1));
            using (WebClient theWebClient = new WebClient())
            {

                try
                {
                    theWebClient.Proxy = null;
                    theWebClient.BaseAddress = "http://website/files/images/";
                    theWebClient.Credentials = new NetworkCredential("user", "pass");
                    theWebClient.DownloadFile("IMG_0417.JPG", "IMG_0417.JPG");
                }
                catch (Exception excep)
                {
                    Response.Write(excep.ToString());
                }
            }
        }

So my question is this:

What is the most simplest way that I can download an image from a URL? If this is something that can be done within JavaScript, that would work too.

I take it you want to download the image to the client's computer , not the server ?

The code you have would download the file to the server. Not what ya want. To send content to the client, you use the Response object.

protected void btnDownload_Click(object sender, ImageClickEventArgs e)
{
    string imagepath= GetImagePath();//blah blah, get this from somewhere
    Response.ContentType= "image/JPEG";
    Response.AddHeader("Content-Disposition", "attachment; filename=myimage.jpeg");
    Response.WriteFile(imagepath);
    Response.End();
}

What this does is gets the path to the image (I assume you know how to do that), then tells it what the content type is (I'm assuming JPEG, but you might have PNG or GIF etc), then added a header that tells it were sending a file with a suggested file name of myimage.jpeg . Then we write the file to the client, and end the response.

  1. Make sure you have full trust level on (web.config) <trust level="Full"/>
  2. On your DownloadFile's second parameter add the code below:
  protected void btnDownload_Click(object sender, ImageClickEventArgs e) { ..... theWebClient.DownloadFile("IMG_0417.JPG", HttpRuntime.AppDomainAppPath + "\\\\IMG_0417.JPG"); ..... } 

Ok the above answer was totally based on user's code issue. the following solution would be the OP's answer. please consider the following solution

  protected void btnDownload_Click(object sender, EventArgs e) { try { linkBtnDownload.Enabled = false; Response.Clear(); Response.ContentType = FileContentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + >FileName); //Writes the specified file directly to an HTTP response output stream, without buffering it in memory Response.TransmitFile(MapPathReverse(URL)); //you can pass your full server path here HttpContext.Current.ApplicationInstance.CompleteRequest(); Response.End(); } catch (Exception ex) { //display error ... } } public static string MapPathReverse(string fullServerPath) { string vPath = @"~\\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, >String.Empty); return vPath; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM