Asp tutorial. net is suitable for beginners to upload files
Today, I made a. aspx page for uploading images from a browser. Of course, after modification, I can also upload files in other formats. The following code is attached:
-- Put a file upload control and a button on the page, and click the button to trigger the content.
// Obtain the file path
String filePath = fileBookPhoto. PostedFile. FileName;
If (string. IsNullOrEmpty (filePath ))
{
Page. ClientScript. RegisterStartupScript (GetType (), "", "alert ('select an image! ') ", True );
Return;
}
// Restrict the format of the uploaded file
// Create a file object based on the complete path of the client file
FileInfo file = new FileInfo (filePath );
// Get the file suffix
String fileType = file. Extension;
// Response. Write ("file type:" + fileType );
If (fileType. equals (". jpeg ") | fileType. equals (". jpg ") | fileType. equals (". gif ") | fileType. equals (". bmp ") | fileType. equals (". png "))
{
// Save the file to the specified directory
// Get the file Name (file. Name)
FileBookPhoto. SaveAs (Server. MapPath ("~ /Image/"+ file. Name ));
// Display the image
// This. imgBookPhoto. ImageUrl = "~ /Image/"+ file. Name;
Book. Photo = file. Name;
}
Else
{
Page. ClientScript. RegisterStartupScript (GetType (), "", "alert ('the image format is incorrect! ') ", True );
Return;
}