您也可以使用 ajaxcontroltoolkit 文件上传器来执行此操作;
<td>
<asp:Label runat="server" ID="myThrobber" Style="display: none; color: black;">
UpLoading....
</asp:Label>
<br />
<Ajax:AsyncFileUpload ID="FileUploadGaurdianPic" runat="server" ThrobberID="myThrobber"
MaximumNumberOfFiles="1"
OnClientUploadComplete="uploadComplete" OnUploadedComplete="FileUploadGaurdianPic_UploadedComplete" Style="margin-left: 0px" />
<asp:Image runat="server" ID="imageGaurdainTemp" /> // temp image to show
</td>
我们有OnUploadedComplete
事件,它是 javascript 文件的函数名。还有用于服务器端处理的 Uploaded_Complete 事件;
protected void FileUploadGaurdianPic_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
// storing the file path in session, in-order to get this in futrue and isnert it into the database. note that i am only getting the path here;
Session["GuardianPic"] = "/Resources/Images/guardian/" + e.FileName;
SaveImage(e.FileName, FileUploadGaurdianPic, 2);
}
// here i am generating the thumbnail,and i am uploading the orignal image to the temp path, if you don't need this, remove it. I am only saving the thumbnail to the orignal path;
private void SaveImage(string FileName, AjaxControlToolkit.AsyncFileUpload uploader, int status)
{
string path = String.Empty;
switch (status)
{
case 1:
path = Server.MapPath("~/Resources/Images/Student/");
break;
case 2:
path = Server.MapPath("~/Resources/Images/guardian/");
break;
}
string name = String.Empty;
string storedPath = String.Empty;
int intThumbWidth = 100;
int intThumbHeight = 100;
// Check whether the file is really a JPEG by opening it
System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
//Create Thumbnail
Bitmap myBitmap = myBitmap = new Bitmap(uploader.PostedFile.InputStream); ;
Bitmap map = new Bitmap(uploader.FileContent);
// Save Thumbnail and Assign it to ThumbUrl out parameter
System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
try
{
string tempPath = Server.MapPath("/Resources/Images/temp/");
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
if (Directory.Exists(path))
{
name = Path.GetFileName(FileName);
storedPath = path + name;
myThumbnail.Save(storedPath);
uploader.SaveAs(tempPath + name);
}
else
{
Directory.CreateDirectory(path);
name = Path.GetFileName(FileName);
storedPath = path + name;
myThumbnail.Save(storedPath);
uploader.SaveAs(tempPath + name);
}
}
catch (Exception ex)
{
throw ex;
}
}
最后,将显示图像的 javascript 函数;
function uploadComplete(sender, args) {
var imgDisplay = $get("imageGaurdainTemp");
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:100px;width:100px";
imgDisplay.src = img.src;
};
img.src = "/Resources/Images/guardian/" + args.get_fileName();
}
我希望这会有所帮助:D