2009-12-06 59 views
0

我有一個FileUpload控件。我正在嘗試保存上傳的文件(圖像),並保存文件的多個縮略圖副本。如何從asp.net中的FileUpload控件創建圖像對象?

當我嘗試這樣的事:

爲System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(PhotoUpload.PostedFile.InputStream);

我得到一個「System.ArgumentException:參數無效。」

我也嘗試使用PhotoUpload.FileBytes從文件字節而不是InputStream創建圖像,但發生同樣的錯誤。

上傳的文件是jpg。我知道這是一個有效的JPG,因爲它保存了原來的好。

編輯:此代碼實際上工作。該參數無效是由於PhotoUpload.PostedFile.InputStream爲空......這似乎是一個完全不同的問題。它看起來像我保存原始的文件上傳流消失後。

編輯:發現FileUpload的InputStream只能被讀取/消耗一次,然後消失。

爲了解決這個問題,我將fileupload文件字節保存到一個字節數組中,並使用字節數組來創建圖像副本。

代碼:

// 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); 
+0

而不是試圖從流中打開文件,爲什麼不打開保存在磁盤上的物理文件? – 2009-12-06 09:30:32

+0

我不保存文件到文件系統。我通過網絡服務將它保存到另一臺服務器上。所以我想通過Web服務2文件:原始(這是工作正常)和縮略圖(還沒有工作)。 – dtc 2009-12-06 09:53:22

回答

2

看一看這個鏈接

ASP Net - How to pass a postedfile to a system.drawing.image

Here's my function call:

uploadAndSizeImage(System.Drawing.Image.FromStream (uploadedFileMD.PostedFile.InputStream))

I'm getting this error:

Exception Details: System.ArgumentException: Invalid parameter used.

Google isn't turning up much though I did find a reference to it possibly being caused by the stream reader being at the end of the stream and me needing to reset it to position one. But that was kind of vague and not really sure if it applies here.

這是否幫助?

編輯:

而且,你嘗試手動閱讀使用的東西的文件中像

System.IO.FileStream fs = System.IO.File.OpenRead(@"Image.JPG"); 
byte[] data = new byte[fs.Length]; 
fs.Read(data, 0, data.Length); 

System.IO.MemoryStream ms = new System.IO.MemoryStream(data); 
System.Drawing.Image image = Image.FromStream(ms); 

還是從節省的FileUpload一個臨時副本,並從文件加載圖像?

+0

謝謝,這確實有幫助,但我現在的問題不是轉換。我發現當我打這個電話時,我的FileUpload內容不見了......在我撥打此電話之前,我保存了文件上傳,之後它不見了......不知道這是否有意義。但現在我需要弄清楚如何保持文件上傳內容。 – dtc 2009-12-06 10:07:07

相關問題