FileUpload.SaveAs(String) Metod

Definition

Sparar innehållet i en uppladdad fil till en angiven sökväg på webbservern.

public:
 void SaveAs(System::String ^ filename);
public void SaveAs(string filename);
member this.SaveAs : string -> unit
Public Sub SaveAs (filename As String)

Parametrar

filename
String

En sträng som anger den fullständiga sökvägen till platsen för servern där den uppladdade filen ska sparas.

Undantag

filename är inte en fullständig sökväg.

Exempel

I följande exempel visas hur du skapar en FileUpload kontroll som utför felkontroll. Innan filen sparas HasFile anropas metoden för att verifiera att en fil som ska laddas upp finns. Dessutom File.Exists anropas metoden för att kontrollera om det redan finns en fil med samma namn i sökvägen. I så fall prefixas namnet på filen som ska laddas upp med ett tal innan SaveAs metoden anropas. Detta förhindrar att den befintliga filen skrivs över.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>FileUpload.SaveAs Method Example</title>
<script runat="server">
        
    protected void  UploadButton_Click(object sender, EventArgs e)
    {
        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile) 
          // Call a helper method routine to save the file.
          SaveFile(FileUpload1.PostedFile);
        else
          // Notify the user that a file was not uploaded.
          UploadStatusLabel.Text = "You did not specify a file to upload.";
    }
            
      void SaveFile(HttpPostedFile file)
      {            
        // Specify the path to save the uploaded file to.
        string savePath = "c:\\temp\\uploads\\";
            
        // Get the name of the file to upload.
        string fileName = FileUpload1.FileName;
            
        // Create the path and file name to check for duplicates.
        string pathToCheck = savePath + fileName;
        
        // Create a temporary file name to use for checking duplicates.
        string tempfileName = "";
            
        // Check to see if a file already exists with the
        // same name as the file to upload.        
        if (System.IO.File.Exists(pathToCheck)) 
        {
          int counter = 2;
          while (System.IO.File.Exists(pathToCheck))
          {
            // if a file with this name already exists,
            // prefix the filename with a number.
            tempfileName = counter.ToString() + fileName;
            pathToCheck = savePath + tempfileName;
            counter ++;
          }
          
          fileName = tempfileName;
          
          // Notify the user that the file name was changed.
          UploadStatusLabel.Text = "A file with the same name already exists." + 
              "<br />Your file was saved as " + fileName;
        }
        else
        {
          // Notify the user that the file was saved successfully.
          UploadStatusLabel.Text = "Your file was uploaded successfully.";
        }

        // Append the name of the file to upload to the path.
        savePath += fileName;
            
        // Call the SaveAs method to save the uploaded
        // file to the specified directory.
        FileUpload1.SaveAs(savePath);
            
      }
        
</script>

</head>
<body>

    <h3>FileUpload.SaveAs Method Example</h3>

    <form id="Form1" runat="server">
   
        <h4>Select a file to upload:</h4>
       
        <asp:FileUpload id="FileUpload1"                 
            runat="server">
        </asp:FileUpload>
            
        <br /><br />
       
        <asp:Button id="UploadButton" 
            Text="Upload file"
            OnClick="UploadButton_Click"
            runat="server">
        </asp:Button>      
        
        <hr />
       
        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>   
         
    </form>

</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>FileUpload.SaveAs Method Example</title>
<script runat="server">
        
      Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            
        ' Before attempting to save the file, verify
        ' that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then
          ' Call a helper method routine to save the file.
          SaveFile(FileUpload1.PostedFile)
        Else
          ' Notify the user that a file was not uploaded.
          UploadStatusLabel.Text = "You did not specify a file to upload."
        End If

      End Sub
        
      Sub SaveFile(ByVal file As HttpPostedFile)
            
        ' Specify the path to save the uploaded file to.
        Dim savePath As String = "c:\temp\uploads\"
            
        ' Get the name of the file to upload.
        Dim fileName As String = FileUpload1.FileName
            
        ' Create the path and file name to check for duplicates.
        Dim pathToCheck As String = savePath + fileName
        
        ' Create a temporary file name to use for checking duplicates.
        Dim tempfileName As String
            
        ' Check to see if a file already exists with the
        ' same name as the file to upload.        
        If (System.IO.File.Exists(pathToCheck)) Then
          Dim counter As Integer = 2
          While (System.IO.File.Exists(pathToCheck))
            ' If a file with this name already exists,
            ' prefix the filename with a number.
            tempfileName = counter.ToString() + fileName
            pathToCheck = savePath + tempfileName
            counter = counter + 1
          End While
          
          fileName = tempfileName
          
          ' Notify the user that the file name was changed.
          UploadStatusLabel.Text = "A file with the same name already exists." + "<br />" + _
                                   "Your file was saved as " + fileName
          
        Else
          
          ' Notify the user that the file was saved successfully.
          UploadStatusLabel.Text = "Your file was uploaded successfully."
          
        End If

        ' Append the name of the file to upload to the path.
        savePath += fileName
            
        ' Call the SaveAs method to save the uploaded
        ' file to the specified directory.
        FileUpload1.SaveAs(savePath)
            
      End Sub
        
  </script>

</head>
<body>

    <h3>FileUpload.SaveAs Method Example</h3>

    <form id="Form1" runat="server">
   
        <h4>Select a file to upload:</h4>
       
        <asp:FileUpload id="FileUpload1"                 
            runat="server">
        </asp:FileUpload>
            
        <br /><br />
       
        <asp:Button id="UploadButton" 
            Text="Upload file"
            OnClick="UploadButton_Click"
            runat="server">
        </asp:Button>      
        
        <hr />
       
        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>   
         
    </form>

</body>
</html>

Kommentarer

Metoden SaveAs sparar innehållet i en uppladdad fil till en angiven sökväg på webbservern.

Kontrollen FileUpload sparar inte automatiskt en fil på servern när användaren har valt den fil som ska laddas upp. Du måste uttryckligen ange en kontroll eller mekanism för att användaren ska kunna skicka den angivna filen. Du kan till exempel ange en knapp som användaren klickar på för att ladda upp filen. Koden som du skriver för att spara den angivna filen ska anropa SaveAs metoden, som sparar innehållet i en fil till en angiven sökväg på servern. SaveAs Vanligtvis anropas metoden i en händelsehanteringsmetod för en händelse som skapar ett inlägg tillbaka till servern. Om du till exempel anger en knapp för att skicka en fil kan koden för att spara filen till servern inkluderas i händelsehanteringsmetoden för klickhändelsen.

När du anropar SaveAs metoden måste du ange den fullständiga sökvägen till katalogen på servern där den uppladdade filen ska sparas. Om du inte uttryckligen anger en sökväg i programkoden utlöses ett HttpException undantag när en användare försöker ladda upp en fil. Det här beteendet hjälper till att skydda filerna på servern genom att användarna inte kan ange en sökväg där de kan spara de filer som de laddar upp.

Innan du anropar SaveAs metoden bör du använda HasFile egenskapen för att kontrollera att FileUpload kontrollen innehåller en fil som ska laddas upp. HasFile Om returnerar trueanropar du SaveAs metoden. Om den returnerar falsevisar du ett meddelande till användaren som anger att kontrollen inte innehåller någon fil. Om du inte anger felhanteringskod för att verifiera att en fil finns, utlöser ett försök att spara en obefintlig fil ett HttpException undantag.

För att ett anrop till SaveAs ska fungera måste ASP.NET-programmet ha skrivåtkomst till katalogen på servern. Det finns två sätt som programmet kan få skrivåtkomst på. Du kan uttryckligen bevilja skrivåtkomst till det konto där programmet körs, i katalogen där de uppladdade filerna sparas. Du kan också öka förtroendenivån för det ASP.NET programmet. För att få skrivåtkomst till programmets körkatalog måste programmet beviljas AspNetHostingPermission objektet med förtroendenivån inställd på AspNetHostingPermissionLevel.Medium värdet. Om du ökar förtroendenivån ökar programmets åtkomst till resurser på servern. Observera att detta inte är en säker metod eftersom en obehörig användare som får kontroll över ditt program också kommer att kunna köras under den här högre förtroendenivån. Det är en bra idé att köra ett ASP.NET program i kontexten för en användare som har de lägsta behörigheter som krävs för att programmet ska kunna köras. Mer information om säkerhet i ASP.NET program finns i Basic Security Practices for Web Applications and ASP.NET Trust Levels and Policy Files.

Gäller för

Se även