星期一, 11月 16, 2009

Jquery plugin : Uploadify 多檔上傳

好用的多檔上傳元件,
伺服端語言可用asp.net或php,
以下範例是一個將相片上傳至相本的的動作~
更多說明請參考網站文件
http://www.uploadify.com/

 <!--uploader-->
<script type="text/javascript" src="../js/swfobject.js"></script>
<script type="text/javascript" src="../js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/uploadify.css"/>
//限制上傳的檔案格式一定要指定fileDesc
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
"uploader": "../js/uploadify.swf",
"script": "../uploadHandler.ashx",
"cancelImg": "../images/cancel.png",
"sizeLimit": 1024000,
"queueID": "fileQueue",
"auto": false,
"fileDesc":"選取上傳的照片",
"fileExt": "*jpeg;*.jpg;*.gif;*.png",
"multi": true,
"onComplete": function(event, queueID, fileObj, response, data) {
if (response == "0")
alert("上傳發生錯誤");
else {
$("#uploadSet").append("<div id=\"fileitem\" >file:" + fileObj.name + " size:" + fileObj.size + "</div>");
}
}
});
});

function Upload() {
$("#uploadSet").html("");
$("#uploadify").uploadifySettings("scriptData", { "aid": $("#ctl00_ContentPlaceHolder1_hiddenAlbum").val() });
$("#uploadify").uploadifyUpload();
}

function CancelUpload() {
$("#uploadify").uploadifyClearQueue();
}

</script>


需注意的是:.net預設的上傳大小為上限值 4096 (4 MB)
因此會產生超出最大要求長度的exception
要再webconfig加入以下設定
例如, Web.config 設定會允許最大 10 MB 的檔案上傳(設跟uploadifyg sizeLimit一樣大):
<System.Web>
<httpRuntime maxRequestLength="10240" />
</System.Web>

*.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>照片上傳</h2>
<p class="help">請上傳小於 1MB 的圖片,僅支援.jpg、.gif、.png等圖片格式</p>
<p>支援多檔上傳</p>
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />

&nbsp;&nbsp;<a href="javascript:Upload()" runat="server">上傳圖片</a>
&nbsp;&nbsp;<a href="javascript:CancelUpload()" >取消選取圖片</a>

<input id="hiddenAlbum" type="hidden" runat="server" />
<div id="uploadSet"></div>
</asp:Content>


uploadHandler.ashx接收上傳的檔案

<%@ WebHandler Language="C#" Class="uploadHandler" %>

using System;
using System.Web;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using BigdControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public class uploadHandler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";

if (context.Request["aid"] == null)
{
context.Response.Write("0");
return;
}

//uploadifySettings post 的 album id
string aid = context.Request["aid"].ToString();

//album directory
string aDirectory = this.GetAlbumDirectory(aid);
if (String.IsNullOrEmpty(aDirectory))
return;//無相簿目錄

string fullFileName = context.Server.MapPath("Album/" + aDirectory + "/");
string fullFileNameThumb = context.Server.MapPath("Album/" + aDirectory + "/thumb/");

for (int i = 0; i < context.Request.Files.Count; i++)
{
HttpPostedFile postedFile = context.Request.Files[i];

string fileFormat = Path.GetExtension(postedFile.FileName);
if (ModuleSecurity.ModuleSecurity.FileChecker(fileFormat,new string[] { ".jpg", ".gif", ".png" }))
{
string orgFileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
//string fileName = orgFileName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;
Random rn = new Random((int)DateTime.Now.Ticks);
string fileName = rn.Next().ToString() + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;

fullFileName = fullFileName + fileName;
fullFileNameThumb = fullFileNameThumb + fileName;

//save photo
postedFile.SaveAs(fullFileName);

//縮圖
postedFile.SaveAs(fullFileNameThumb);
ImageProcessing.Save(fullFileNameThumb,
ImageProcessing.ImagePreviewThumb(fullFileNameThumb, 100, 100, Color.White, InterpolationMode.High, SmoothingMode.HighQuality));

//add photo
this.AddAlbumPhoto(aid, fileName);
}
}

context.Response.Write("1");
}

public bool IsReusable {
get {
return false;
}
}


/// <summary>
/// 取得相簿目錄
/// </summary>
/// <param name="aid">相簿id</param>
/// <returns></returns>
public string GetAlbumDirectory(string aid)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("select ActivityAlbumDirectory from ActivityAlbum where ActivityAlbumID=@aid",sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
string direcdtory = sqlCmd.ExecuteScalar().ToString();
sqlConn.Close();

return direcdtory;
}

/// <summary>
/// 新增相片
/// </summary>
/// <param name="aid">相簿id</param>
/// <param name="photo">相本檔名</param>
public void AddAlbumPhoto(string aid, string photo)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("insert into ActivityPhoto(ActivityPhotoAID,ActivityPhotoFile)values(@aid,@photo) ", sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
sqlCmd.Parameters.Add("photo", SqlDbType.NVarChar).Value = photo;
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}

}

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails