Bagikan melalui


FileUpload.SaveAs(String) Metode

Definisi

Menyimpan isi file yang diunggah ke jalur tertentu pada server Web.

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

Parameter

filename
String

String yang menentukan jalur lengkap lokasi server untuk menyimpan file yang diunggah.

Pengecualian

filename bukan jalur lengkap.

Contoh

Contoh berikut menunjukkan cara membuat FileUpload kontrol yang melakukan pemeriksaan kesalahan. Sebelum file disimpan, HasFile metode dipanggil untuk memverifikasi bahwa file yang akan diunggah ada. Selain itu, metode ini dipanggil File.Exists untuk memeriksa apakah file yang memiliki nama yang sama sudah ada di jalur. Jika ya, nama file yang akan diunggah diawali dengan angka sebelum metode dipanggil SaveAs . Ini mencegah file yang ada ditimpa.

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

Keterangan

Metode menyimpan SaveAs konten file yang diunggah ke jalur tertentu di server Web.

FileUpload Kontrol tidak secara otomatis menyimpan file ke server setelah pengguna memilih file yang akan diunggah. Anda harus secara eksplisit memberikan kontrol atau mekanisme untuk memungkinkan pengguna mengirimkan file yang ditentukan. Misalnya, Anda dapat memberikan tombol yang diklik pengguna untuk mengunggah file. Kode yang Anda tulis untuk menyimpan file yang ditentukan harus memanggil SaveAs metode , yang menyimpan konten file ke jalur tertentu di server. Biasanya, SaveAs metode ini dipanggil dalam metode penanganan peristiwa untuk peristiwa yang menaikkan posting kembali ke server. Misalnya, jika Anda menyediakan tombol untuk mengirimkan file, kode untuk menyimpan file ke server kemudian dapat disertakan di dalam metode penanganan peristiwa untuk peristiwa klik.

Saat Anda memanggil SaveAs metode , Anda harus menentukan jalur lengkap direktori di server untuk menyimpan file yang diunggah. Jika Anda tidak secara eksplisit menentukan jalur dalam kode aplikasi Anda, HttpException pengecualian akan dilemparkan saat pengguna mencoba mengunggah file. Perilaku ini membantu menjaga file di server tetap aman, dengan tidak mengizinkan pengguna menentukan jalur untuk menyimpan file yang mereka unggah.

Sebelum memanggil SaveAs metode , Anda harus menggunakan HasFile properti untuk memverifikasi bahwa FileUpload kontrol berisi file untuk diunggah. Jika mengembalikan HasFiletrue, panggil SaveAs metode . Jika mengembalikan false, tampilkan pesan kepada pengguna yang menunjukkan bahwa kontrol tidak berisi file. Jika Anda tidak memberikan kode penanganan kesalahan untuk memverifikasi bahwa file ada, upaya untuk menyimpan file yang tidak ada akan melemparkan HttpException pengecualian.

Agar panggilan ke SaveAs berfungsi, aplikasi ASP.NET harus memiliki akses tulis ke direktori di server. Ada dua cara agar aplikasi bisa mendapatkan akses tulis. Anda dapat secara eksplisit memberikan akses tulis ke akun tempat aplikasi berjalan, di direktori tempat file yang diunggah akan disimpan. Atau, Anda dapat meningkatkan tingkat kepercayaan yang diberikan ke aplikasi ASP.NET. Untuk mendapatkan akses tulis ke direktori yang dijalankan untuk aplikasi, aplikasi harus diberikan AspNetHostingPermission objek dengan tingkat kepercayaan yang diatur ke AspNetHostingPermissionLevel.Medium nilai . Meningkatkan tingkat kepercayaan meningkatkan akses aplikasi ke sumber daya di server. Perhatikan bahwa ini bukan pendekatan yang aman, karena pengguna jahat yang mendapatkan kontrol atas aplikasi Anda juga akan dapat berjalan di bawah tingkat kepercayaan yang lebih tinggi ini. Ini adalah praktik terbaik untuk menjalankan aplikasi ASP.NET dalam konteks pengguna yang memiliki hak istimewa minimum yang diperlukan agar aplikasi dapat berjalan. Untuk informasi selengkapnya tentang keamanan dalam aplikasi ASP.NET, lihat Praktik Keamanan Dasar untuk Aplikasi Web dan ASP.NET Tingkat Kepercayaan dan File Kebijakan.

Berlaku untuk

Lihat juga