c#多圖片上傳並產生縮圖的執行個體代碼

來源:互聯網
上載者:User

前台代碼:

複製代碼 代碼如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
li
{
list-style: none;
padding-top: 10px;
}
</style>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
function ValidImage(id, msg) {
$(id).parent().append("<span>" + msg + "</span>");
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<div>
<ul>
<li>
<input type="file" id="upload1" name="upload" />
</li>
<li>
<input type="file" id="upload2" name="upload" />
</li>
<li>
<input type="file" id="upload3" name="upload" />
</li>
<li>
<input type="file" id="upload4" name="upload" /></li>
<li>
<input type="file" id="upload5" name="upload" />

</li>
<li>
<input type="submit" id="btnPostFile" runat="server" onserverclick="btnPostFile_ServerClick" value="開始上傳" />
</li>
</ul>
</div>
</form>
</body>
</html>

前台就是幾個控制項和一個ValidImage方法。

後台代碼:

複製代碼 代碼如下:

protected void btnPostFile_ServerClick(object sender, EventArgs e)
{
string filePath = Server.MapPath("/uploadImg");
const int size = 5242880;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile postFile = Request.Files[i];
string uploadFileID = string.Format("#upload{0}", i + 1); //當前的上傳控制項ID,因為jquery要調用就加了#
string msg = null; //提示資訊
if (postFile.FileName.Trim().Length <= 0)
{
continue;
}
if (postFile.ContentLength > size)
{
msg = "檔案太大";
Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);//將提示資訊發送到用戶端
continue;
}
string savePath = Path.Combine(filePath, postFile.FileName); //圖片的儲存地址
if (!File.Exists(savePath))
{
postFile.SaveAs(Path.Combine(filePath, postFile.FileName)); //如果檔案不存在就儲存
}
else
{
msg = "檔案" + postFile.FileName + "已經存在";
Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);//將提示資訊發送到用戶端
continue;
}
if (IsImg(savePath)) //通過IsImg方法驗證檔案是否是圖片,或者格式是否正確
{
SmallImg(postFile.InputStream, postFile.FileName);
}
else
{
msg = "只能上傳JGP、PNG類型的圖片,請檢查檔案格式是否正確";
Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);//將提示資訊發送到用戶端
File.Delete(savePath); //如果不是圖片就刪除
}
}
}
}

複製代碼 代碼如下:

#region 驗證上傳檔案的格式
/// <summary>
/// 驗證上傳檔案是否是圖片
/// </summary>
/// <param name="FilePath">檔案的儲存路徑</param>
/// <returns></returns>
private bool IsImg(string FilePath)
{
using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{
bool result = false;
BinaryReader br = new BinaryReader(fs, System.Text.Encoding.UTF8);
string strImg = "";
byte buffer;
try
{
buffer = br.ReadByte();
strImg = buffer.ToString();
buffer = br.ReadByte();
strImg += buffer.ToString();
}
catch
{
fs.Close();
br.Close();

}
if (strImg == "255216" || strImg == "13780")//說明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
result = true;
}
return result;
}
}
#endregion

複製代碼 代碼如下:

#region 將圖片產生縮圖
/// <summary>
/// 產生縮圖
/// </summary>
private void SmallImg(Stream oStream, string FileName)
{
using (System.Drawing.Image img = System.Drawing.Image.FromStream(oStream))
{
int newWidth = 100;
int newHeight = 80;
int oldWidth = img.Width;
int oldHeight = img.Height;
if (oldWidth > oldHeight)
{
newHeight = (int)Math.Floor((double)oldHeight * (double)newWidth / (double)oldWidth);
}
else
{
newWidth = (int)Math.Floor((double)oldWidth * (double)newHeight / (double)oldHeight);
}
using (Bitmap bmp = new Bitmap(newWidth, newHeight))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Transparent);
g.InterpolationMode = InterpolationMode.High;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(img, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, oldWidth, oldHeight), GraphicsUnit.Pixel);
string newFileName = Path.GetFileNameWithoutExtension(FileName) + "_small" + Path.GetExtension(FileName); //縮圖名稱
string filePath = Server.MapPath("/uploadImg/") + newFileName;
bmp.Save(filePath);
}
}

}
}
#endregion

代碼有很多需要改進的地方,希望大家多多指點。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.