Image uploading method based on C winform
- 2020-06-23 01:49:33
- OfStack
The example implementation in this article uploads a picture to the specified folder and displays it in the PictrueBox control on the form.
The specific function code is as follows:
private void btnUpload_Click(object sender, EventArgs e)
{
// create 1 A dialog box object
OpenFileDialog ofd = new OpenFileDialog();
// Set the title for the dialog box
ofd.Title = " Please select the image to upload ";
// Set the format of the filtered image
ofd.Filter = " Image format |*.jpg";
// Sets whether multiple selection is allowed
ofd.Multiselect = false;
// If you hit the OK button
if (ofd.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
// Get the full path to the file (including the suffix after the name)
string filePath = ofd.FileName;
// Displays the file path in a text box
txtImgUrl.Text = filePath;
// Find the file name like" 1.jpg "The one in front." \ The location of the"
int position = filePath.LastIndexOf("\\");
// Extract the file name from the full path. 1.jpg "
string fileName = filePath.Substring(position+1);
// Read the selected file and return 1 A flow
using (Stream stream = ofd.OpenFile())
{
// create 1 To write to the resulting file stream (note: create 1 Called" Images "Folder, if is using relative path, must be in this program Degug Create under directory
// If it's an absolute path, you can put it there. I'm using a relative path.)
using (FileStream fs = new FileStream(@"./Images/" + fileName, FileMode.CreateNew))
{
// Copies the resulting file stream to the write stream
stream.CopyTo(fs);
// Writes data from the write stream to a file
fs.Flush();
}
//PictrueBOx Displays the image, at which point the image has been copied 1 Copy of the Images Under folder, you're uploading
// As for uploading to other places, you can change your mind. This is just a demonstration
pbShow.ImageLocation = @"./Images/" + fileName;
}
}
}