无法在用户端下载文件夹中下载图像

时间:2017-06-13 06:45:17

标签: c# asp.net image c#-4.0 asp.net-web-api

无法在用户端下载文件夹中下载图像。我已经尝试了很多方法来解决这个问题。我还给出了用户的文件路径,并尝试下载asp:image control" url" ...整个代码已执行但未将图像保存在文件夹中。我尝试了更多解决方案,但没有工作。有任何建议可以帮助我... 我被困在了......提前谢谢你......

 //To show image from URl on asp:image control on click of gridview button 
 protected void Redirect1_Click(object sender, EventArgs e)
{
    var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;
    BookingNO = GridView1.Rows[rowIndex].Cells[0].Text;
    var request = WebRequest.Create("http:-#-//?a=" + BookingNO + "&b=2" + "");
    using (var response = request.GetResponse())
    using (var stream = response.GetResponseStream())
    {
         LoadImage.ImageUrl = "http:-#-//?a=" + BookingNO + "&b=2" + "";
        LoadImage.Visible = true;
        md.Visible = true;
        LoadImage.ToolTip = "Image of Order Number. " + BookingNO + "";
        Download.Visible = true;

    }
}

//按钮点击下载图片

 public void Download_click(object sender, EventArgs e)
 {
     try
     {
         string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
         string pathDownload = Path.Combine(pathUser, "Downloads");
         string url = LoadImage.ImageUrl;

         byte[] data;
         using (WebClient client = new WebClient())
         {
             data = client.DownloadData(url);
         }
         File.WriteAllBytes(pathDownload + BookingNO + ".jpg", data);
         ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Order Number " + BookingNO + " Image Saved');", true);
     }
     catch (Exception ex)
     {
     }
}

1 个答案:

答案 0 :(得分:1)

您无法强制在客户端计算机上保存文件,并且绝对不能在特定文件夹中保存文件。您只能将文件移交给用户,让浏览器保存该文件或询问用户在何处以及是否保存文件。

顺便说一下,您的代码并没有下载单个图片,它最多可以设置图片控件的源位置。

如果要将图像写入输出流(当图像为字节数组时),则可以执行以下操作:

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"file.png\"");
HttpContext.Current.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
相关问题