System.IO.Stream
我想像这样使用 AjaxFileUpload获取文件。这是经典的 FileUpload 组件。
System.IO.Stream theStream = fileUpload.PostedFile.InputStream;
有人可以告诉我该怎么做吗?
如果您正在处理UploadComplete
事件,那么您可以从事件参数的GetStreamContents
(作为流)和GetContents
(作为字节数组)方法中获取流AjaxFileUploadEventArgs
例如
protected void afu_OnUploadComplete(object sender, AjaxFileUploadEventArgs file)
{
using (var stream = file.GetStreamContents())
{
// Read the stream...
}
}
您可以查看源代码中可用的内容AjaxFileUploadEventArgs
- 远不止文档中的内容。
您可以暂时保存文件,然后读取它以获取您的 FileStream。它可能有点脏,但它对我有用。
VB.NET:
Dim tempPath As String = System.IO.Path.GetTempFileName()
yourAjaxFileUpload.SaveAs(tempPath)
Using fs As FileStream = File.OpenRead(tempPath)
'Do stuff with fs here
End Using
File.Delete(tempPath)
C#:
string tempPath = System.IO.Path.GetTempFileName();
yourAjaxFileUpload.SaveAs(tempPath);
using (FileStream fs = File.OpenRead(tempPath)) {
//do stuff with fs here
}
File.Delete(tempPath);
如果有人想在您保存图像之前进行转换(例如:Png 到 jpg)。下面可能对ajaxcontroltoolkit中的asyncfileuploader有所帮助
Protected Sub FileUploadComplete(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim id As String = Session("MBRId")
Dim contentType As String = AsyncFileUploadProfileImage.ContentType
If (contentType = "image/jpeg" Or contentType = "image/png") Then
Dim filename As String = System.IO.Path.GetFileName(AsyncFileUploadProfileImage.FileName)
Dim TOjpegImage = System.Drawing.Image.FromStream(AsyncFileUploadProfileImage.FileContent)
TOjpegImage.Save(Server.MapPath("img_prof/" + id + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
Dim Ext As String = System.IO.Path.GetExtension(AsyncFileUploadProfileImage.FileName)
'Commented working save due to conversion of image above
' AsyncFileUploadProfileImage.SaveAs(Server.MapPath("img_prof/") + id + Ext)
lblMesg.Text = "File Uploaded Successfully"
Else
lblMesg.Text = "We support only images of type jpg and png"
End If
Catch ex As Exception
iHelperClasses.ErrorLogger.ErrorWriter("Method:FileUploadComplete()Error:" + ex.Message)
End Try
End Sub