2011-07-26 36 views
1

我在做一個項目:使用AsyncFileUpload控制上傳文件並將其存儲

Front end - Visual Studio 2010 

Technology : C# 

Back end - Sql Server 2005 

我想上傳使用AsyncFileUpload控制文件,並存儲到「〜/圖片/」文件夾中。

腳本:

<asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
    <ContentTemplate> 
     <asp:ScriptManager ID="ScriptManager1" runat="server"> 
     </asp:ScriptManager> 
     <asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
      onuploadedcomplete="AsyncFileUpload1_UploadedComplete"/> 
    </ContentTemplate> 

代碼背後:

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e) 
{ 
    if (AsyncFileUpload1.HasFile) 
    { 
     AsyncFileUpload1.SaveAs("~/Image/" + AsyncFileUpload1.FileName); 
     Label2.Text = "Recieved " + AsyncFileUpload1.FileName + " Content Type" + AsyncFileUpload1.PostedFile.ContentType; 
    } 
} 

但每次叫其顯示運行時錯誤:

The SaveAs method is configured to require a rooted path, and the path '~\Image\Filename.jpg' is not rooted. 

我可以知道錯誤及其SOLU灰。

由於提前,

尼基爾

+0

這是[確切的重複](http://stackoverflow.com/questions/1350977/the-saveas-method-is-configured-to-require-a-rooted-path-and-the-path -圖片) –

回答

0

我想通了:

table width="100%" style="font: 8pt verdana"> 
       <tr width="100%"> 
       <td width="40%"> 
        <asp:FileUpload ID="FileUpload1" runat="server" /> 
        <asp:HiddenField ID="HiddenField1" runat="server" /> 
       </td> 
       <td width="40%"><asp:Label ID="lblPicStatus" runat="server"></asp:Label></td> 
       <td> 
       <asp:Button ID="Button2" runat="server" Text="Upload" BackColor="White" 
         BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" 
         onclick="Button2_Click"/></td> 
       </tr> 
</table> 

代碼背後,

protected void Button2_Click(object sender, EventArgs e) 
{ 

    try 
    { 
     con.Open(); 
     if (FileUpload1.HasFile) 
     { 
      String fileExt = Path.GetExtension(FileUpload1.FileName); 
      if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png") 
      { 
       String path = "~/Image/" + FileUpload1.FileName; 
       cmd.CommandText = "update " + HttpContext.Current.User.Identity.Name + " set image = '" + path + "'"; 
       cmd.Connection = con; 
       cmd.ExecuteNonQuery(); 
       FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName); 
       Response.Redirect(Request.RawUrl); 
      } 
      else 
      { 
       lblPicStatus.Text = "File to be uploaded is not an image"; 
      } 
      con.Close(); 
     } 
    } 

    catch (Exception a) 
    { 
     Response.Write(a.Message); 
    } 
} 
0
String path = "~/Image/" + FileUpload1.FileName; 

應該是這樣的:

String path = Server.MapPath("~/Image/") + FileUpload1.FileName; 
相關問題