<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebUploaderFileByBaidu2.aspx.cs" Inherits="WebApplication1.WebUploaderFileByBaidu2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>WebUploader文件上传示例</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<link href="Scripts/webuploader/webuploader.css" rel="stylesheet" />
<script type="text/javascript" src="Scripts/webuploader/webuploader.min.js"></script>
<link href="https://cdn.bootcss.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="Scripts/style.css" rel="stylesheet" />
<link href="Scripts/demo.css" rel="stylesheet" />
<link href="Scripts/font-awesome.css" rel="stylesheet" />
<script type="text/javascript">
var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
// 文件上传
jQuery(function () {
var $ = jQuery,
$list = $('#fileList'),
$btn = $('#ctlBtn'),
state = 'pending',
uploader;
uploader = WebUploader.create({
// 不压缩image
resize: false,
// swf文件路径
swf: applicationPath + 'Script/webuploader/Uploader.swf',
// 文件接收服务端。
server: 'UploaderFileByBaidu.ashx',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker'
});
// 当有文件添加进来的时候
uploader.on('fileQueued', function (file) {
$list.append('<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>');
});
// 文件上传过程中创建进度条实时显示。
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=" 0%">' +
'</div>' +
'</div>').appendTo($li).find('.progress-bar');
}
$li.find('p.state').text('上传中');
$percent.css('width', percentage * 100 + '%');
});
uploader.on('uploadSuccess', function (file) {
$('#' + file.id).find('p.state').text('已上传');
});
uploader.on('uploadError', function (file) {
$('#' + file.id).find('p.state').text('上传出错');
});
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').fadeOut();
});
uploader.on('all', function (type) {
if (type === 'startUpload') {
state = 'uploading';
} else if (type === 'stopUpload') {
state = 'paused';
} else if (type === 'uploadFinished') {
state = 'done';
}
if (state === 'uploading') {
$btn.text('暂停上传');
} else {
$btn.text('开始上传');
}
});
$btn.on('click', function () {
if (state === 'uploading') {
uploader.stop();
} else {
uploader.upload();
}
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="col-md-10">
<div class="row">文件上传示例:</div>
<div class="row">
<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="fileList" class="uploader-list"></div>
<div class="btns">
<div id="picker" class="btn btn-primary">选择文件</div>
</div>
</div>
</div>
<div class="row">
</div>
<div class="row"> <button id="ctlBtn" class="btn btn-default">开始上传</button></div>
</div>
<div>
</div>
</div>
</body>
</html>
以上代码最后的显示结果如下图:
图8.
2) 接收前端用户上传的文件,并把文件保存到指定目录中。UploaderFileByBaidu.ashx文件中使用默认的代码,不需要添加任何代码。UploaderFileByBaidu.ashx.cs文件的代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// UploaderFileByBaidu 的摘要说明
/// </summary>
public class UploaderFileByBaidu : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentEncoding = Encoding.UTF8;
if (context.Request["REQUEST_METHOD"] == "OPTIONS")
{
context.Response.End();
}
SaveFile();
}
/// <summary>
/// 文件保存操作
/// </summary>
/// <param name="basePath"></param>
private void SaveFile(string basePath = "~/Upload/Images/")
{
basePath = FileHelper.GetUploadPath();
string Datedir = DateTime.Now.ToString("yy-MM-dd");
string updir = basePath + "\" + Datedir;
string extname = string.Empty;
string fullname = string.Empty;
string filename = string.Empty;
HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
if (files.Count == 0)
{
var result = "{"jsonrpc" : "2.0", "error" : "保存失败","id" : "id"}";
System.Web.HttpContext.Current.Response.Write(result);
}
if (!Directory.Exists(updir))
Directory.CreateDirectory(updir);
var suffix = files[0].ContentType.Split('/');
var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
var _temp = System.Web.HttpContext.Current.Request["name"];
if (!string.IsNullOrEmpty(_temp))
{
filename = _temp;
}
else
{
Random rand = new Random(24 * (int)DateTime.Now.Ticks);
filename = rand.Next() + "." + _suffix;
}
fullname = string.Format("{0}\{1}",updir , filename);
files[0].SaveAs(fullname);
var _result = "{"jsonrpc" : "2.0", "result" : null, "id" : "" + filename + ""}";
System.Web.HttpContext.Current.Response.Write(_result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
第四步:文件辅助类
/// <summary>
///FileHelper 的摘要说明
/// </summary>
public class FileHelper
{
public FileHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 获取上传目录
/// </summary>
/// <returns></returns>
public static string GetUploadPath()
{
string path = HttpContext.Current.Server.MapPath("~/");
string dirname = GetDirName();
string uploadDir = path + "\" + dirname;
CreateDir(uploadDir);
return uploadDir;
}
/// <summary>
/// 获取临时目录
/// </summary>
/// <returns></returns>
public static string GetTempPath()
{
string path = HttpContext.Current.Server.MapPath("~/");
string dirname = GetTempDirName();
string uploadDir = path + "\" + dirname;
CreateDir(uploadDir);
return uploadDir;
}
private static string GetDirName()
{
return System.Configuration.ConfigurationManager.AppSettings["uploaddir"];
}
private static string GetTempDirName()
{
return System.Configuration.ConfigurationManager.AppSettings["tempdir"];
}
public static void CreateDir(string path)
{
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
}
第五步,Web.config文件配置信息。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<appSettings>
<add key="uploaddir" value="upload" />
<add key="tempdir" value="temp" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows" />
<httpRuntime maxRequestLength="2147483647" appRequestQueueLimit="1200" executionTimeout="1200"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
</system.web>
<system.webServer>
<security>
<requestFiltering >
<requestLimits maxAllowedContentLength="2147483647" ></requestLimits>
</requestFiltering>
</security>
</system.webServer>
</configuration>
第六步,在进行上传之后,文件保存在对应的日期目录下。如下图。
到这,DEMO下载地址:https://dwz.cn/fgXtRtnu