看看下面的代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div>
<input type="file" name="uploadPicture" id="uploadPicture">
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default7 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string baseImageLocation = Server.MapPath("Images\\");
HttpFileCollection uploads = HttpContext.Current.Request.Files;
HttpPostedFile file = uploads["uploadPicture"];
string fileExt = Path.GetExtension(file.FileName).ToLower();
string fileName = Path.GetFileName(file.FileName);
if (fileName != "")
{
if (fileExt == ".jpg" || fileExt == ".gif")
file.SaveAs(baseImageLocation + fileName);
}
}
}
編輯
可以從HttpPostedFile得到的圖像尺寸,如下
int size = file.ContentLength;
和用於圖像的高度和寬度可以用下面的函數
private void GetHeightAndWidht(string image)
{
Bitmap bmp = new Bitmap(image);
int height = bmp.Height;
int width = bmp.Width;
}
'HttpFileCollection uploads = HttpContext.Current.Request.Files;' 總是返回一個空集合... – Danpe 2011-05-05 21:19:49
@Danpe:請檢查您是否有在表單部分設置enctype屬性(enctype =「multipart/form-data」) – 2011-05-06 04:45:04