Loading an image and fixing / improving its size with <input type = "file">?
I am using ASP.NET 3.5 C # and I would like to get an image that the user is trying to load from
<input type="file" name="uploadPicture" id="uploadPicture"> Can I just use:
Request.Form["uploadPicture"];
What's next?
I never played with uploading files using forms, I want to save this file in my File system and save the database path.
I also need to check the format, size and sizes and maybe even resize if possible.
Thanks Dan
+3
2 answers
Check the following code
<%@ 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);
}
}
}
EDIT
you can get image size from HttpPostedFile as below
int size = file.ContentLength;
and for the height and width of the image you can use the following function
private void GetHeightAndWidht(string image)
{
Bitmap bmp = new Bitmap(image);
int height = bmp.Height;
int width = bmp.Width;
}
0