Aracılığıyla paylaş


FileUpload.SaveAs(String) Yöntem

Tanım

Karşıya yüklenen dosyanın içeriğini Web sunucusunda belirtilen yola kaydeder.

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

Parametreler

filename
String

Karşıya yüklenen dosyanın kaydedildiği sunucunun konumunun tam yolunu belirten dize.

Özel durumlar

filename tam bir yol değildir.

Örnekler

Aşağıdaki örnekte, hata denetimi gerçekleştiren bir FileUpload denetimin nasıl oluşturulacağı gösterilmektedir. Dosya kaydedilmeden önce, HasFile karşıya yüklenecek bir dosyanın mevcut olduğunu doğrulamak için yöntemi çağrılır. Ayrıca, File.Exists aynı ada sahip bir dosyanın yolda zaten var olup olmadığını denetlemek için yöntemi çağrılır. Varsa, karşıya yüklenecek dosyanın adı, yöntem çağrılmadan önce SaveAs bir sayı ile önek olarak eklenir. Bu, var olan dosyanın üzerine yazılmasını engeller.

<%@ 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>

Açıklamalar

yöntemi, SaveAs karşıya yüklenen bir dosyanın içeriğini Web sunucusunda belirtilen yola kaydeder.

Denetim FileUpload , kullanıcı karşıya yüklenecek dosyayı seçtikten sonra dosyayı otomatik olarak sunucuya kaydetmez. Kullanıcının belirtilen dosyayı göndermesine izin vermek için açıkça bir denetim veya mekanizma sağlamanız gerekir. Örneğin, kullanıcının dosyayı karşıya yüklemek için tıklatabileceği bir düğme sağlayabilirsiniz. Belirtilen dosyayı kaydetmek için yazdığınız kod, bir dosyanın içeriğini sunucudaki belirtilen yola kaydeden yöntemini çağırmalıdır SaveAs . Genellikle yöntemi, SaveAs sunucuya geri gönderi oluşturan bir olay için olay işleme yönteminde çağrılır. Örneğin, dosya göndermek için bir düğme sağlarsanız, dosyayı sunucuya kaydetme kodu tıklama olayının olay işleme yöntemine eklenebilir.

yöntemini çağırdığınızda SaveAs , karşıya yüklenen dosyanın kaydedildiği sunucuda dizinin tam yolunu belirtmeniz gerekir. Uygulama kodunuzda açıkça bir yol belirtmezseniz, HttpException kullanıcı bir dosyayı karşıya yüklemeyi denediğinde bir özel durum oluşur. Bu davranış, kullanıcıların karşıya yükledikleri dosyaların kaydedildiği bir yol belirtmesine izin vermeyerek sunucudaki dosyaların güvenli kalmasına yardımcı olur.

yöntemini çağırmadan SaveAs önce, denetimin HasFile karşıya yüklenecek bir dosya içerdiğini FileUpload doğrulamak için özelliğini kullanmanız gerekir. HasFile döndürürse trueyöntemini çağırınSaveAs. döndürürse false, kullanıcıya denetimin dosya içermediğini belirten bir ileti görüntüler. Bir dosyanın var olduğunu doğrulamak için hata işleme kodu sağlamazsanız, var olmayan bir dosyayı kaydetme girişimi bir HttpException özel durum oluşturur.

çağrısının SaveAs çalışması için ASP.NET uygulamasının sunucudaki dizine yazma erişimi olmalıdır. Uygulamanın yazma erişimi elde etmenin iki yolu vardır. Uygulamanın çalışmakta olduğu hesaba, karşıya yüklenen dosyaların kaydedileceği dizinde açıkça yazma erişimi vekleyebilirsiniz. Alternatif olarak, ASP.NET uygulamaya verilen güven düzeyini artırabilirsiniz. Uygulamanın yürütme dizinine yazma erişimi almak için, uygulamaya güven düzeyi değerine ayarlanmış nesne verilmelidir AspNetHostingPermission AspNetHostingPermissionLevel.Medium . Güven düzeyini artırmak, uygulamanın sunucudaki kaynaklara erişimini artırır. Uygulamanızın denetimini alan kötü amaçlı bir kullanıcı da bu yüksek güven düzeyi altında çalışabileceğinden, bunun güvenli bir yaklaşım olmadığını unutmayın. Uygulamanın çalışması için gereken en düşük ayrıcalıklara sahip bir kullanıcı bağlamında bir ASP.NET uygulaması çalıştırmak en iyi uygulamadır. ASP.NET uygulamalarda güvenlik hakkında daha fazla bilgi için bkz. Web Uygulamaları ve ASP.NET Güven Düzeyleri ve İlke Dosyaları için Temel Güvenlik Uygulamaları.

Şunlara uygulanır

Ayrıca bkz.