我使用 ASP .NET 3.5 C#,我想获取用户尝试上传的图片
<input type="file" name="uploadPicture" id="uploadPicture">
我可以使用:
Request.Form["uploadPicture"];
接下来呢?
从来没有玩过使用表单上传文件,我希望将此文件保存在我的文件系统中并将路径保存在数据库中。
我还需要检查格式、大小和尺寸,如果可能的话,甚至可能调整它的大小。
谢谢,丹
我使用 ASP .NET 3.5 C#,我想获取用户尝试上传的图片
<input type="file" name="uploadPicture" id="uploadPicture">
我可以使用:
Request.Form["uploadPicture"];
接下来呢?
从来没有玩过使用表单上传文件,我希望将此文件保存在我的文件系统中并将路径保存在数据库中。
我还需要检查格式、大小和尺寸,如果可能的话,甚至可能调整它的大小。
谢谢,丹
像这样使用
HttpFileCollection files = Request.Files;
查看以下代码
<%@ 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;
}