一、需求
1.需求:在Web端实现上传图片功能的基础上,增加预览图片并裁剪图片功能。
2.未更改之前如下图所示:
3.更改后的功能,当点击浏览(原生input type='file'控件)选择图片上传后,可以调整裁剪框大小及位置,点击上传按钮实现裁剪并上传,点击确定后将裁剪后的图片路径赋值给父页面的文章缩略图后的input。
二、实现
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpFileBox.aspx.cs" Inherits="PublicPage_UpFileBox" %>
<!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 id="Head1" runat="server">
<title>文件上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="jquery.Jcrop.min.css" rel="stylesheet" />
<script src="../artDialog/artDialog.source.js?skin=default"></script>
<script src="../artDialog/plugins/iframeTools.js"></script>
<script src="../artDialog/msgBox.js" type="text/javascript"></script>
<script src="jquery.min.js"></script>
<script src="jquery.Jcrop.min.js"></script>
<script src="jquery.color.js"></script>
<script type="text/javascript">
art.dialog.data('FileName', '<%=FileName %> ');
art.dialog.data('FileSize', '<%=FileSize %> ');
art.dialog.data('FilePath', '<%=FilePath %> ');
</script>
</head>
<body style="background-color: White">
<form id="form1" runat="server">
<table border="0" cellpadding="1" cellspacing="0" style="height: 550px; width: 650px">
<tr height="350">
<td colspan="2">
<div id="imgContainer" style="width: 640px; height: 350px; border: 1px solid #c0c0c0">
<h3>点击浏览按钮,请选择要上传的图片</h3>
</div>
<input type="hidden" name="x1" id="x1" value="" runat="server" />
<input type="hidden" name="x2" id="x2" value="" runat="server" />
<input type="hidden" name="y1" id="y1" value="" runat="server" />
<input type="hidden" name="y2" id="y2" value="" runat="server" />
<input type="hidden" name="w" id="w" value="" runat="server" />
<input type="hidden" name="h" id="h" value="" runat="server" />
</td>
</tr>
<tr height="30">
<tr height="30">
<td align="left">
<input id="PictureUrl" runat="server" name="File1" type="file" οnchange="bindImgSrc()" /></td>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<td width="81" align="left">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" Width="60px" CausesValidation="False" /></td>
</tr>
<td class="inputexplain" style="padding-left: 5px" colspan="2">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" BackColor="#FFC0C0"
BorderWidth="1px" ControlToValidate="PictureUrl" Display="Dynamic" ErrorMessage="请选择您要上传的文件"
SetFocusOnError="True" Width="138px"></asp:RequiredFieldValidator>
<asp:Label ID="LB_PicError" runat="server" BackColor="#FFC0C0" BorderWidth="1px"
ForeColor="Red" Text="文件上传失败!" Visible="False" Width="343px"></asp:Label>
<asp:Label
ID="LB_Success" runat="server" BackColor="#C0FFFF" BorderWidth="1px" ForeColor="Teal"
Text="文件上传成功!" Visible="False" Width="122px"></asp:Label><asp:Label ID="LB_Fail"
runat="server" BackColor="#FFC0C0" BorderWidth="1px" ForeColor="Red" Text="文件上传失败!"
Visible="False" Width="126px"></asp:Label><br>
<%=hint %></td>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
function bindImgSrc() {
var path = document.forms[0].PictureUrl.value;//获取input type='file'的路径value
$('#imgContainer').html("<img src='" + path + "' alt='Alternate Text' width='640px' height='350px' id='target' />");
cutImg();
}
function cutImg() {
var jcrop_api;
$('#target').Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [45, 55, 607, 320],//固定裁剪选框的大小
onChange: showCoords, //当裁剪选框发生改变
}, function () {
jcrop_api = this;
});
}
function showCoords(c) {
$('#x1').val(c.x);//通过<input type='hidden' runat='server'>给后台提供选框的宽高,x1、y1、x2、y2为定义选框的四个角坐标,w、h为定义的宽高
$('#y1').val(c.y);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
$('#w').val(c.w);
$('#h').val(c.h);
};
</script>
4.后台代码接受前台图片路径及裁剪大小参数,实现图片裁剪和保存。这里主要看UPFile()方法的处理过程。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DingKit;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Net;
public partial class PublicPage_UpFileBox : System.Web.UI.Page
{
public string FileName = "";
public string FileSize = "";
public string FileExp = "";
public string FileNewName = "";
public string FilePath = "";
public string hint = "";
public string UpDirKey = "";
public string UpDir = "";
public string FileType = "";
public string IsKeepOldName = "";
protected void Page_Load(object sender, EventArgs e)
{
UpDir = CFun.GetParam("UpDir");
FileType = CFun.GetParam("FileType");
IsKeepOldName = CFun.GetParam("IsKeepOldName");
if (!IsPostBack)
{
}
}
/// <summary>
/// 文件类型是否允许
/// </summary>
/// <param name="FileExp">文件类型</param>
/// <returns>是否允许</returns>
public static bool IsExpAllow(string File_Exp,string FileExp)
{
string[] Arr_FileExp;
Char[] split = { '|', ',',',' };
Arr_FileExp = File_Exp.Split(split, 100);
//获取当前目录下的文件
foreach (string file in Arr_FileExp)
{
if (file.ToLower() == FileExp.ToLower())
return true;
}
return false;
}
/// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
private bool UPFile()
{
if (PictureUrl.PostedFile.ContentLength == 0)
{
LB_PicError.Text = "上传路径不能为空!";
LB_PicError.Visible = true;
return false;
}
else
{
LB_PicError.Visible = false;
string strfilePath = PictureUrl.PostedFile.FileName;
//取得文件名(抱括路径)里最后一个"."的索引
FileExp = CFile.GetFileExp(strfilePath);
FileName = CFile.GetFileName(strfilePath);
//判断文件的类型是否是允许
if (FileType == "")
{
if (CFile.IsExpAllow(FileExp) == false)
{
LB_PicError.Text = "上传失败,图片格式必须是:" + CFile.File_Exp;
LB_PicError.Visible = true;
return false;
}
}
else
{
if (IsExpAllow(FileType,FileExp) == false)
{
LB_PicError.Text = "上传失败,文件格式必须是:" + FileType;
LB_PicError.Visible = true;
return false;
}
}
double size = PictureUrl.PostedFile.ContentLength / 1024.0;
FileSize = size.ToString();
if (CFile.IsSizeAllow(PictureUrl.PostedFile.ContentLength.ToString()) == false)
{
LB_PicError.Text = "上传失败,您上传的文件大小为" + FileSize + "K,最大允许大小为:" + CFile.File_Sizem;
LB_PicError.Visible = true;
//CFun.JsAlerT("上传失败,您上传的文件超过系统允许范围!");
return false;
}
//这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复
DateTime now = DateTime.Now;
string fName = CFun.Left(FileName, FileName.Length - 1 - FileExp.Length);
if (IsKeepOldName == "1")
{
FileNewName = fName;
}
else
{
FileNewName = fName + "_" + now.DayOfYear.ToString() + PictureUrl.PostedFile.ContentLength.ToString();
}
//注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里""必须用""代替
if (UpDir == "null" || UpDir == "")
{
UpDir = CFile.UpDir;
}
if (CFun.Left(UpDir,1) == @"/")
{
UpDir = CFun.Right(UpDir, UpDir.Length - 1);
}
if (CFun.Right(UpDir,1) == @"/")
{
UpDir = CFun.Left(UpDir, UpDir.Length - 1);
}
FilePath = UpDir + "/" + FileNewName + "." + FileExp;//"/" +
string fileUpDir = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "/" + UpDir;
if (!System.IO.Directory.Exists(fileUpDir))
{
System.IO.Directory.CreateDirectory(fileUpDir);
}
Bitmap b;
Graphics g;
int x11 = Convert.ToInt32(x1.Value);
int x22 = Convert.ToInt32(x2.Value);
int y11 = Convert.ToInt32(y1.Value);
int y22 = Convert.ToInt32(y2.Value);
int ww = Convert.ToInt32(w.Value);
int hh = Convert.ToInt32(h.Value);
using (System.Drawing.Image img = System.Drawing.Image.FromFile(PictureUrl.PostedFile.FileName))//Image.FromFile()的参数不能是uri格式
{
b = new Bitmap(ww, hh, img.PixelFormat);//创建指定大小的Bitmap对象
b.SetResolution(img.HorizontalResolution, img.VerticalResolution);//设置分辨率
g = Graphics.FromImage(b); //绘图区域
g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置Graphics的高质量插补模式
g.PixelOffsetMode = PixelOffsetMode.Half; //设置像素便宜规则以高速锯齿消除
g.DrawImage(img, new Rectangle(0, 0, ww, hh), new Rectangle(x11, y11, ww, hh), GraphicsUnit.Pixel);//以指定规则绘制图片实现裁剪
img.Dispose();//释放内存
}
b.Save(fileUpDir + "/" + FileNewName + "." + FileExp);//Image.Save()保存到指定文件或流
b.Dispose();
g.Dispose();
return true;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (UPFile() == true)
{
LB_Success.Visible = true;
LB_Fail.Visible = false;
//CFun.HideSuccHint();
hint = "";
hint += "文件名称:<font Color=#990000>" + FileName + "</font><br>";
hint += "文件大小:<font Color=#990000>" + FileSize + "KB</font><br>";
hint += "上传路径:<font Color=#990000>" + FilePath + "</font><br>";
}
else
{
LB_Success.Visible = false;
LB_Fail.Visible = true;
hint = "";
hint += "文件名称:<font Color=#990000>" + FileName + "</font><br>";
hint += "文件大小:<font Color=#990000>" + FileSize + "KB</font><br>";
hint += "上传路径:<font Color=#990000>" + FilePath + "</font><br>";
}
}
}
三、总结
总结一下过程中遇到的问题:
1.前台给后台传值:可以使用input type=‘hidden’添加runat=‘server’属性编程服务器控件,使用js给该控件赋值,后台接受该控件value;
2.后台给前台传值:在后台定义一个public变量,前台通过js获取该变量,例如var filepath = ‘<%=FilePath%>’;
3.后台Image.FromFile(path)参数不支持Uri格式问题:Image.FromFile(path)的path应该为本地文件路径,获取的是input type='file'的value,例如PictureUrl.PostedFile.FileName
3.解决后台Image.FromFile(path)参数不支持Uri格式问题:如果你必须传入一个url,那么请改用Image.FromStream()方法,例如:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();//获得响应
Image img = Image.FromStream(response.GetResponseStream());///实例化,得到img
4.保存文件到指定目录方式的两种方式:
4.1)PictureUrl.PostedFile.SaveAs(fileUpDir + "/" + FileNewName + "." + FileExp); //input id='PictureUrl' type='file' runat='server'控件 使用SaveAs()
4.2)b.Save(fileUpDir + "/" + FileNewName + "." + FileExp);//Image.Save()保存到指定文件或流
5.该软件使用了artdialog对话框组件,很多时候我们在接手一个新项目时,需要了解一下他组件的基本使用,对话框组件中应该包括父子页面传值的函数,要善于使用手头的各种工具;
6.很多时候应该多多梳理逻辑,调试javascript脚本要善于使用alert()和console.log()。
7.很多时候应该学会拒绝。