批量上传在web应用中非常常见,而基于<input type="file">控件的原理,没有办法通过在js中新增file控件来达到多附件上传的目的,这时候,我们需要一个易用的批量上传文件的控件。
swfupload是一个客户端文件上传控件,最初由Vinterwebb.se开发,基于flash和js技术,提供一个富功能的上传控件,它包含以下特点:
1. 可选择多个文件上传
2. 类似ajax局部刷新效果
3. 可显示上传进度
4. 选择文件时,可以过滤文件类型(据我所知,使用file控件很难做到这点)
5. 良好的浏览器兼容性,兼容一些js库,如:jquery, prototype,支持flash 8,9
6. 上传图片时,可先预览效果
使用起来也比较方便,以下将描述它的配置过程,并在文章最后提供源码的下载链接。
【资源下载】
你可以在swfupload官网上找到最新的版本,注意下载.net的版本。
【配置步骤】
1. 引用必要的文件,以下三个文件是必须的:
swfupload.swf、swfupload.js、handlers.js
包含进系统,注意路径(批量上传页面与三个文件的相对路径),例如上传文件页面在网站根目录,而三个文件放置在Content/js下,那么,引入路径应该是:
<script type="text/javascript" src="Content/js/swfupload.js"></script>
<script type="text/javascript" src="Content/js/handlers.js"></script>
swf文件路径会在配置中使用到,swfupload上传页面配置如下:
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "upload.aspx",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>"
},
// File Upload Settings
file_size_limit: "2 MB",
file_types: "*.jpeg; *.jpg; *.png; *.gif",
file_types_description: "Images",
file_upload_limit: "0", // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
file_queue_error_handler: fileQueueError,
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: uploadSuccess,
upload_complete_handler: uploadComplete,
// Button settings
button_image_url: "Content/images/XPButtonNoText_160x22.png",
button_placeholder_id: "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text: '<span class="button">选择图片<span class="buttonSmall">[大小(2MB Max)]</span></span>',
button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 1,
button_text_left_padding: 5,
// Flash Settings
flash_url: "Content/js/swfupload.swf", // Relative to this file
custom_settings: {
upload_target: "divFileProgressContainer"
},
// Debug Settings
debug: false
});
}
</script>
upload_url即生成缩略图和图片缓存的处理页面。
post_params这个属性不能随意修改,否则,图片将无法缓存至session中,导致生成缩略图后,没有办法真正上传图片。
怎么配置这些属性?顾名思义,基本上可以猜测出它的用途,在此不过多累述。在handlers.js中包含以上方法的响应,如果你有特殊需求,可以考虑改造这些方法。
官网的批量上传图片的demo只是在页面生成缩略图,并把图片信息缓存在session中,并没有实际上传的操作,我在网上找到一个改造的例子,添加了上传图片和清理缓存的功能,注:它所谓的上传图片其实是上传的缩略图的图片,不会上传原型图片,应该算是功能上的bug,我在上面做了一个小小的修改,即生成了缩略图,又可以上传原型图片,修改代码如下:
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Image thumbnail_image = null;
System.Drawing.Image original_image = null;
System.Drawing.Bitmap final_image = null;
System.Drawing.Bitmap real_image = null;
System.Drawing.Graphics graphic = null;
System.Drawing.Graphics real_graphic = null;
MemoryStream ms = null;
try
{
// Get the data
HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
// Retrieve the uploaded image
original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
// Calculate the new width and height
int width = original_image.Width;
int height = original_image.Height;
int target_width = 100;
int target_height = 100;
int new_width, new_height;
float target_ratio = (float)target_width / (float)target_height;
float image_ratio = (float)width / (float)height;
if (target_ratio > image_ratio)
{
new_height = target_height;
new_width = (int)Math.Floor(image_ratio * (float)target_height);
}
else
{
new_height = (int)Math.Floor((float)target_width / image_ratio);
new_width = target_width;
}
new_width = new_width > target_width ? target_width : new_width;
new_height = new_height > target_height ? target_height : new_height;
// Create the thumbnail
// Old way
//thumbnail_image = original_image.GetThumbnailImage(new_width, new_height, null, System.IntPtr.Zero);
// We don't have to create a Thumbnail since the DrawImage method will resize, but the GetThumbnailImage looks better
// I've read about a problem with GetThumbnailImage. If a jpeg has an embedded thumbnail it will use and resize it which
// can result in a tiny 40x40 thumbnail being stretch up to our target size
real_image = new System.Drawing.Bitmap(width, height); // ÕæÊµÍ¼Æ¬´óС
real_graphic = System.Drawing.Graphics.FromImage(real_image);
real_graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
real_graphic.DrawImage(original_image, 0, 0, width, height);
final_image = new System.Drawing.Bitmap(target_width, target_height);
graphic = System.Drawing.Graphics.FromImage(final_image);
graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));
int paste_x = (target_width - new_width) / 2;
int paste_y = (target_height - new_height) / 2;
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
//graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height);
graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);
// Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
ms = new MemoryStream();
final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
MemoryStream real_ms = new MemoryStream();
real_image.Save(real_ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// Store the data in my custom Thumbnail object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff")
+ jpeg_image_upload.FileName.Substring(jpeg_image_upload.FileName.LastIndexOf("."));
Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer());
Thumbnail real_thumb = new Thumbnail(thumbnail_id, real_ms.GetBuffer());
List<Thumbnail> real_thumbnails = Session["real_file_info"] as List<Thumbnail>;
if (real_thumbnails == null) {
real_thumbnails = new List<Thumbnail>();
}
real_thumbnails.Add(real_thumb);
Session["real_file_info"] = real_thumbnails;
// Put it all in the Session (initialize the session if necessary)
List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;
if (thumbnails == null)
{
thumbnails = new List<Thumbnail>();
Session["file_info"] = thumbnails;
}
thumbnails.Add(thumb);
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch(Exception ex)
{
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured£º" + ex.Message);
Response.End();
}
finally
{
// Clean up
if (final_image != null) final_image.Dispose();
if (graphic != null) graphic.Dispose();
if (original_image != null) original_image.Dispose();
if (thumbnail_image!= null )thumbnail_image.Dispose();
if (ms != null) ms.Close();
Response.End();
}
上传图片的操作如下:
HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
if (Session["real_file_info"] != null)
{
try
{
List<Thumbnail> thumbnails = Session["real_file_info"] as List<Thumbnail>;
string UploadPath = Server.MapPath("~/Upload/");
// 可缓存Thumbnail数据类,在上传后,统一保存图片完整路径至数据库
foreach (Thumbnail img in thumbnails)
{
FileStream fs = new FileStream(UploadPath + img.ID, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(img.Data);
bw.Close();
fs.Close();
}
// 操作数据库
Session.Clear();
Response.Write("<script>alert('上传图片成功!');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('上传图片失败:" + ex.Message + "');</script>");
}
}
由于后面会提供源码下载地址,这里只列出关键部分的代码,不列完整代码了。
运行效果图: