Uploading Image and Fixing/Veryfing it's size

2019-07-04 21:39发布

问题:

I Use ASP .NET 3.5 C#, and i whould like to get the picture that the user trying to upload from

<input type="file" name="uploadPicture" id="uploadPicture"> Can i just use:

Request.Form["uploadPicture"];

And what next?

Never played around with uploading files with forms, I wish to save this file on my File System and save the path on the database.

I need also to check the format, size and dimensions, and maybe even resize it if possible.

Thanks, Dan

回答1:

Check out 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 image height and width you can used the following function

 private void GetHeightAndWidht(string image)
    {
        Bitmap bmp = new Bitmap(image);
        int height = bmp.Height;
        int width = bmp.Width;
    }


回答2:

Use like this

HttpFileCollection files = Request.Files;