前端html代码:uploadDemo.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Uploadify</title>
<script src="scripts/jquery/jquery-1.10.2.min.js"></script>
<script src="scripts/uploadify.v3.2.1/jquery.uploadify.min.js"></script>
<link href="scripts/uploadify.v3.2.1/uploadify.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function () {
$("#uploadify").uploadify({
'debug': false,//调试开关
//'fileSizeLimit': '100KB',//上传文件限制
'swf': '/scripts/uploadify.v3.2.1/uploadify.swf', //指定swf文件
//后台处理的页面
'uploader': '/tools/uploadHandler.ashx',
'folder': '',
//按钮显示的文字
'buttonText': '上传图片',
//显示的高度和宽度,默认 height 30;width 120
//'height': 15,
//'width': 80,
//上传文件的类型 默认为所有文件 'All Files' ; '*.*'
//在浏览窗口底部的文件类型下拉菜单中显示的文本
'fileTypeDesc': 'Image Files',
//允许上传的文件后缀
'fileTypeExts': '*.gif; *.jpg; *.png',
//发送给后台的其他参数通过formData指定
//'formData': { 'someKey': 'someValue', 'someOtherKey': 1 },
//上传文件页面中,你想要用来作为文件队列的元素的id, 默认为false 自动生成, 不带#
//'queueID': 'fileQueue',
//选择文件后自动上传
'auto': true,
//设置为true将允许多文件上传
'multi': true,
'onUploadSuccess': function (file, data, response) { //上传成功的动作
//alert('这几个文件上传成功' + file.name + ' 已经成功上传 with a response of ' + response + ':' + data);
//alert(data);
var newData = $.parseJSON(data);
$("#imglist").append("<img src='" + newData.file + "' width='200'>");
//alert(newData.file);
},
'onCancel': function (file) { //取消时的动作
//alert('文件' + file.name + ' 已取消.');
}
});
});
</script>
</head>
<body>
<div id="fileQueue">
</div>
<input type="file" name="uploadify" id="uploadify" />
<p>
<a href="javascript:$('#uploadify').uploadify('upload','*')">上传</a>|
<a href="javascript:$('#uploadify').uploadify('cancel')">取消上传</a>
</p>
<div id="imglist"></div>
</body>
</html>
后端处理文件:hander.ashx
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DTcms.Common;
namespace DTcms.Web.tools
{
/// <summary>
/// uploadHandler 的摘要说明
/// </summary>
public class uploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
HttpPostedFile file = context.Request.Files["Filedata"];
string uploadPath =HttpContext.Current.Server.MapPath("/UploadFiles/" + "\\");
if (file != null)
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string fileExt = Utils.GetFileExt(file.FileName); //文件扩展名,不含“.”
int fileSize = file.ContentLength; //获得文件大小,以字节为单位
string fileName = file.FileName.Substring(file.FileName.LastIndexOf(@"\") + 1); //取得原文件名
string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名
file.SaveAs(uploadPath + newFileName);
//下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
//context.Response.Write("1");
context.Response.Write("{\"file\":\"/UploadFiles/"+newFileName+"\"}");
}
else
{
context.Response.Write("0");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4