上传图片,并使用<输入类型="file">修正/调整其大小
本文关键字:quot file 修正 调整 类型 输入 | 更新日期: 2023-09-27 17:54:05
我使用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);
}
}
}
编辑
你可以从httppostdfile获取图像大小,如下所示
int size = file.ContentLength;
对于图像的高度和宽度,可以使用以下函数
private void GetHeightAndWidht(string image)
{
Bitmap bmp = new Bitmap(image);
int height = bmp.Height;
int width = bmp.Width;
}