我有一个文件上传控件。我正在尝试保存上载的文件(图像),并保存该文件的几个缩略图副本。
当我尝试这样的方法时:
system.drawing.image imgoriginal=system.drawing.image.fromstream(photoupload.postedfile.inputstream);
我得到一个“System.ArgumentException:参数无效。”
我还尝试使用photoupload.file bytes从文件字节(而不是inputstream)创建图像,但发生了相同的错误。
上载的文件是JPG。我知道这是一个有效的JPG,因为它保存了原始的OK。
编辑:这个代码确实有效。参数无效,因为photoupload.postedfile.inputstream为空…这似乎是一个完全不同的问题。在我保存原始文件之后,文件上传流就消失了。
编辑:发现文件上传的输入流只能读取/使用一次,然后就消失了。
为了解决这个问题,我将fileupload filebytes保存到一个字节数组中,并使用字节数组创建图像的副本。
代码:
// Copy the FileBytes into a byte array
byte[] imageData = PhotoUpload.FileBytes;
// Create a stream from the byte array if you want to save it somewhere:
System.IO.Stream myStream = new System.IO.MemoryStream(imageData);
// Or create an image from the stream as many times as needed:
System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(myStream);