Upload on Picture Box Control and Save Stream File

Answered
0
0

Hello Guys,

I’m struggling to upload an image into a picture box control and save it in the project folder. I have two procedures, one for upload to the picture box and the other one to save to the project folder. The problem is that one of the two procedures does not do the job well, in my case the save procedure seems to copy the image correctly but when you look at the file, it shows with 0 kb size. If I put a comment on the LoadFile procedure, it saves well. Am I missing something? See the code below. Thanks!

string sFileUploadPath;
public frmtest()
{
InitializeComponent();
}
private void frmtest_Load(object sender, EventArgs e)
{
string sDirectory = Path.GetDirectoryName(Application.ExecutablePath);
sFileUploadPath = sDirectory.Replace("\\bin", string.Empty) + "\\Uploads\\";
}
private void upload1_Uploaded(object sender, UploadedEventArgs e)
{
LoadFile(e.Files);
SaveStreamAsFile(sFileUploadPath, e.Files[0].InputStream, e.Files[0].FileName);
}
void SaveStreamAsFile(string filePath, Stream inputStream, string fileName)
{
DirectoryInfo info = new DirectoryInfo(filePath);
if (!info.Exists)
{
info.Create();
}
string path = Path.Combine(filePath, fileName);
using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
{
inputStream.CopyTo(outputFileStream);
}
}
private void LoadFile(System.Web.HttpFileCollection files)
{
if (files == null)
return;
if (files.Count == 0)
{
this.pictureBox1.Image = null;
}
else
{
this.pictureBox1.Image = GetImageFromStream(files[0].InputStream);
}
}
private Image GetImageFromStream(System.IO.Stream stream)
{
System.IO.MemoryStream mem = new System.IO.MemoryStream();
stream.CopyTo(mem, 1024);
mem.Position = 0;
return Image.FromStream(mem);
}

 

  • You must to post comments
Best Answer
0
0

Hi Carlos

The problem was that after using the sequence to load the image in the image box this is left at the end position.

Solution is just to rewind it

Regars and happy coding

  • Carlos Lino
    Ohh I’m sorry my bad. Thanks for checking for me. Much appreciated
  • You must to post comments
0
0

See sample project uploaded. Many thanks!

Attachment
  • You must to post comments
0
0

Hi  Carlos

Could you please, upload your sample project to check it. You must delete the bin and obj folders before zip

Thanks 🙂

  • You must to post comments
Showing 3 results
Your Answer

Please first to submit.