How to check file size on upload

后端 未结 6 1001
别那么骄傲
别那么骄傲 2020-12-08 11:22

Whats the best way to check the size of a file during upload using asp.net and C#? I can upload large files by altering my web.config without any problems. My issues arises

6条回答
  •  温柔的废话
    2020-12-08 12:05

    You can do the checking in asp.net by doing these steps:

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        // Specify the path on the server to
        // save the uploaded file to.
        string savePath = @"c:\temp\uploads\";
    
        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile)
        {                
            // Get the size in bytes of the file to upload.
            int fileSize = FileUpload1.PostedFile.ContentLength;
    
            // Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
            if (fileSize < 2100000)
            {
    
                // Append the name of the uploaded file to the path.
                savePath += Server.HtmlEncode(FileUpload1.FileName);
    
                // Call the SaveAs method to save the 
                // uploaded file to the specified path.
                // This example does not perform all
                // the necessary error checking.               
                // If a file with the same name
                // already exists in the specified path,  
                // the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath);
    
                // Notify the user that the file was uploaded successfully.
                UploadStatusLabel.Text = "Your file was uploaded successfully.";
            }
            else
            {
                // Notify the user why their file was not uploaded.
                UploadStatusLabel.Text = "Your file was not uploaded because " + 
                                         "it exceeds the 2 MB size limit.";
            }
        }   
        else
        {
            // Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload.";
        }
    }
    

提交回复
热议问题