Html部分
<head>
<meta name="viewport" content="width=device-width" />
<title>UpDemo</title>
<link href="~/Content/webuploader/webuploader.css" rel="stylesheet" />
<script src="~/Content/theme/assets/global/plugins/jquery.min.js"></script>
<script src="~/Content/webuploader/webuploader.js"></script>
</head>
<body>
<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<div id="picker">选择文件</div>
<button id="ctlBtn" class="btn btn-default">开始上传</button>
</div>
</div>
Js部分
$(document).ready(function () {
initUpload();
});
function initUpload() {
var $ = jQuery;
var $list = $('#thelist');
var uploader = WebUploader.create({
// GUID=GUID;
// 选完文件后,是否自动上传。
auto: false,
// swf文件路径
swf: '../Content/webuploader/Uploader.swf',
// 文件接收服务端。
//server: applicationPath + 'PublicInfoManage/Upload/Upload',
server: '../../FileUpload/Upload',//"http://localhost:47542" +
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
chunked: true,//开始分片上传
chunkSize: 2048000,//每一片的大小
//formData: {
// guid: GUID //自定义参数,待会儿解释
//},
// 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
resize: false
});
// 当有文件被添加进队列的时候
uploader.on('fileQueued', function (file) {
$list.append('<li id="' + file.id + '" class="list-group-item">' +
'<span class="fileName" dataValue="">' + file.name + '</span>' +
'<span class="state" style=\" margin-left: 10px;\">等待上传</span>' +
'<span class="filepath" dataValue="0" style=\" margin-left: 10px;display: none;\"></span>' +
'<span class="download" style="margin-left:20px;"></span>' +
'<span class="webuploadDelbtn"style=\"float: right;display: none; \">删除<span>' +
'</li>');
});
// 文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress', function (file, percentage) {
var $li = $('#' + file.id),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if (!$percent.length) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo($li).find('.progress-bar');
}
$li.find('span.state').text('上传中');
$percent.css('width', percentage * 100 + '%');
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on('uploadSuccess', function (file, response) {
var $li = $('#' + file.id);
console.log(response);
if (response.Code == "1") {
//$('#' + file.id).find('p.state').text('已上传');
$.post('../../FileUpload/SaveInfo', { fileName: file.name, fileUrl: response.Data, fileType: file.ext, fileSize: file.size }, function (data) {
$li.find('span.state').html("上传成功");
$li.find('span.filepath').attr("dataValue", 1);
$li.find('span.fileName').attr("dataValue", data.filename);
$li.find('span.fileName').html(data.filename);
$li.find('span.download').html("<a href=\"../../doc/" + response.Data+ "\">下载</a>")
$li.find('span.webuploadDelbtn').show();
$li.find('span.filepath').html(data.filepath);
//增加列表存储
//files.push(data);
});
}
else
{
}
});
// 文件上传失败,显示上传出错。
uploader.on('uploadError', function (file, reason) {
$('#' + file.id).find('p.state').text(reason);
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').fadeOut();
});
//所有文件上传完毕
uploader.on("uploadFinished", function () {
//提交表单
});
//开始上传
$("#ctlBtn").click(function () {
uploader.upload();
});
//删除
$list.on("click", ".webuploadDelbtn", function () {
debugger
var $ele = $(this);
var id = $ele.parent().attr("id");
var file = uploader.getFile(id);
uploader.removeFile(file);
$ele.parent().remove();
//移除数组
var destFile = findFile(file.name)
var index = files.indexOf(destFile);
if (index > -1) {
files.splice(index, 1);
}
});
}
保存图片方法
[HttpPost]
public string Upload()
{
Message msg = new Message();
string url = "";
if (Request.Files.Count > 0)
{
HttpPostedFileBase uploadFile = Request.Files[0] as HttpPostedFileBase;
var now = DateTime.Now;
string filePath = Server.MapPath("~/doc/file/" + @now.ToString("yyyyMMdd") + "/");
string ViewPath = "/file/" + @now.ToString("yyyyMMdd") + "/";
url = UploadHelper.SaveFile(uploadFile, filePath, ViewPath);
}
if (string.IsNullOrEmpty(url))
{
msg.Code = "0";
msg.Msg = "图片上传失败";
}
else if (url.Contains("图片尺寸过大"))
{
msg.Code = "0";
msg.Msg = "图片尺寸过大";
}
else
{
//item.Url = picHelper.GetPictureUrl(item.ID, item.Url, targetSize: 600, showDefaultPicture: true, isSquare: true);
msg.Code = "1";
msg.Msg = "上传成功";
msg.Data = url;
}
return msg.ToJsonString();
}
//这里是进行二进制到Base64的转换
public static string ByteToBase64(byte[] ByteArry, int Start, int Length)
{
string Result;
Result = System.Convert.ToBase64String(ByteArry, Start, Length);
return Result;
}
public static bool CheckImage(int Width, int Height)
{
bool Result = true;
//int width = 1000, height = 2000;
//if (Height > height)//Width > width ||
//{
// Result = false;
//}
return Result;
}
public static string SaveFile(HttpPostedFileBase uploadFile, string filePath, string ViewPath)
{
NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
List<string> allowFiles = new List<string>();
allowFiles.Add("png");
allowFiles.Add("jpg");
allowFiles.Add("jpeg");
allowFiles.Add("bmp");
allowFiles.Add("gif");
string fileName = "";
int FileLength = uploadFile.ContentLength;
if (FileLength > 10 * 1024 * 1024)
{
return "图片尺寸过大";
}
if (uploadFile.ContentType.Contains("image"))
{
//判断图片的长和宽
Byte[] FileByteArray = new byte[FileLength];//图象文件临时存储到Byte数组里
Stream StreamObject = uploadFile.InputStream;//建立数据流对象
StreamObject.Read(FileByteArray, 0, FileLength);
//转换成Base64格式
string Base64String = ByteToBase64(FileByteArray, 0, FileByteArray.Length);
//建立图片对象
System.Drawing.Image MyImage = System.Drawing.Image.FromStream(StreamObject);
bool CheckImageResult = CheckImage(MyImage.Width, MyImage.Height);
if (!CheckImageResult)
{
return "图片尺寸过大";
}
}
string FileName = uploadFile.FileName;
int lastIndex = FileName.LastIndexOf('.');
string FileType = FileName.Substring(lastIndex);
var now = DateTime.Now;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
int rand = new Random().Next(100, 999);
fileName = now.ToString("yyyyMMddhhmmssffff") + rand + FileType;
uploadFile.SaveAs(filePath + fileName);
//filePath = filePath.Replace("\\", "/");
//string[] ContentType = uploadFile.ContentType.Split('/');
return ViewPath + fileName;
}
将图片信息保存到表中
public string SaveInfo(string fileName,string fileUrl,string fileType,int fileSize=0,string RelID="")
{
Message msg = new Message();
if (string.IsNullOrEmpty(fileUrl) || string.IsNullOrEmpty(fileName)||string.IsNullOrEmpty(fileType))
{
msg.Code = "0";
msg.Msg = "参数传递错误";
return msg.ToJsonString();
}
SysFileBLL FileHelper = new SysFileBLL();
SysFile file = new SysFile();
file.FileName = fileName;
file.FSize = fileSize;
file.FType = fileType;
file.RelID = RelID;
file.Url = fileUrl;
file.IsPic = 0;
bool sign = FileHelper.Save(file);
if (sign)
{
msg.Code = "1";
msg.Msg = "保存成功";
msg.Data = file.ID;
}
else
{
msg.Code = "0";
msg.Msg = "保存失败";
}
return msg.ToJsonString();
}