FileUpload.HasFile Propiedad
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Obtiene un valor que indica si el control FileUpload contiene un archivo.
public:
property bool HasFile { bool get(); };
[System.ComponentModel.Browsable(false)]
public bool HasFile { get; }
[<System.ComponentModel.Browsable(false)>]
member this.HasFile : bool
Public ReadOnly Property HasFile As Boolean
Valor de propiedad
Es true
si FileUpload contiene un archivo; en caso contrario, es false
.
- Atributos
Ejemplos
En el ejemplo siguiente se muestra cómo crear un FileUpload control que realiza la comprobación de errores. Antes de guardar el archivo, HasFile se llama al método para comprobar que el control contiene un archivo que se va a cargar. Además, se llama al File.Exists método para comprobar si ya se produce un archivo con el mismo nombre en la ruta de acceso. Si es así, el nombre del archivo que se va a cargar tiene como prefijo un carácter de subrayado antes de llamar al SaveAs método . Esto impide que se sobrescriba el archivo existente.
<%@ 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>
Comentarios
La HasFile propiedad obtiene un valor que indica si el FileUpload control contiene un archivo que se va a cargar. Utilice esta propiedad para comprobar que existe un archivo para cargar antes de realizar operaciones en el archivo. Por ejemplo, antes de llamar al SaveAs método para guardar el archivo en el disco, use la HasFile propiedad para comprobar que el archivo existe. Si HasFile devuelve true
, llame al SaveAs método . Si devuelve false
, muestra un mensaje al usuario que indica que el control no contiene un archivo.