现如今,世面上流行着许多前端上传组件,例如:Uploadify(http://www.uploadify.com/),Fine Uploader,等等。这篇博客从头开始,介绍如何在ASP.NET MVC中使用Fine Uploader。
 
 
代码结果如下图所示,可以选择本地文件之后点击上传,文件会被传输到服务器根目录下的Upload文件夹中(文件夹的名称是代码中定义的)。
 

 
Step By Step Process:
 
1. 在官网的下载页面下载Fine Uploader压缩包。https://fineuploader.com/customize.html
 

2. 新建MVC工程并将刚刚下载之后的解压文件夹添加到项目中。
 

3.在Models中添加类文件 FineUpload.cs 和 FineUploadResult.cs,Controller中添加UploaderController。
(这里参考了Github上的Server样例 https://github.com/FineUploader/server-examples,至于这两个类文件是否应该放在Models文件夹下有待商榷。)
 
 using System.IO;
using System.Web.Mvc; namespace FineUploaderTest.Web.Model
{
[ModelBinder(typeof(ModelBinder))]
public class FineUpload
{
public string Filename { get; set; }
public Stream InputStream { get; set; } public void SaveAs(string destination, bool overwrite = false, bool autoCreateDirectory = true)
{
if (autoCreateDirectory)
{
var directory = new FileInfo(destination).Directory;
if (directory != null) directory.Create();
} using (var file = new FileStream(destination, overwrite ? FileMode.Create : FileMode.CreateNew))
InputStream.CopyTo(file);
} public class ModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.RequestContext.HttpContext.Request;
var formUpload = request.Files.Count > ; // find filename
var xFileName = request.Headers["X-File-Name"];
var qqFile = request["qqfile"];
var formFilename = formUpload ? request.Files[].FileName : null; var upload = new FineUpload
{
Filename = xFileName ?? qqFile ?? formFilename,
InputStream = formUpload ? request.Files[].InputStream : request.InputStream
}; return upload;
}
} }
}

FineUpload.cs

 using System.Web.Mvc;
using Newtonsoft.Json.Linq; namespace FineUploaderTest.Web.Model
{
/// <remarks>
/// Docs at https://github.com/Widen/fine-uploader/blob/master/server/readme.md
/// </remarks>
public class FineUploaderResult : ActionResult
{
public const string ResponseContentType = "text/plain"; private readonly bool _success;
private readonly string _error;
private readonly bool? _preventRetry;
private readonly JObject _otherData; public FineUploaderResult(bool success, object otherData = null, string error = null, bool? preventRetry = null)
{
_success = success;
_error = error;
_preventRetry = preventRetry; if (otherData != null)
_otherData = JObject.FromObject(otherData);
} public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = ResponseContentType; response.Write(BuildResponse());
} public string BuildResponse()
{
var response = _otherData ?? new JObject();
response["success"] = _success; if (!string.IsNullOrWhiteSpace(_error))
response["error"] = _error; if (_preventRetry.HasValue)
response["preventRetry"] = _preventRetry.Value; return response.ToString();
}
}
}

FineUploadResult.cs

 using FineUploaderTest.Web.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace FineUploaderTest.Web.Controllers
{
public class UploaderController : Controller
{
// GET: Uploader
public ActionResult Index()
{
return View();
} [HttpPost]
public FineUploaderResult UploadFile(FineUpload upload)
{
var dir = Server.MapPath("~/Upload");
int pos1 = upload.Filename.LastIndexOf("\\");
string fileName = pos1 == - ? upload.Filename : upload.Filename.Substring(pos1 + , upload.Filename.Length - pos1 - );
string storeName = Guid.NewGuid() + fileName;
var filePath = Path.Combine(dir, storeName);
try
{
upload.SaveAs(filePath);
ViewBag.SourcePath = filePath;
}
catch (Exception ex)
{
return new FineUploaderResult(false, error: ex.Message);
}
// the anonymous object in the result below will be convert to json and set back to the browser
return new FineUploaderResult(true, new { extraInformation = filePath });
}
}
}

UploaderController.cs

添加代码之后的文件夹结构:
 

4. 重写Home文件夹下的Index.cshtml页面
 
 @{
ViewBag.Title = "Test Fine Upload";
} <h3>Test Fine Upload</h3> <link href="~/fine-uploader/fine-uploader-new.css" rel="stylesheet" /> <style>
#trigger-upload {
color: white;
background-color: #00ABC7;
font-size: 14px;
padding: 7px 20px;
background-image: none;
} #Query {
color: white;
background-color: #00ABC7;
font-size: 14px;
padding: 7px 20px;
background-image: none;
} #fine-uploader-manual-trigger .qq-upload-button {
margin-right: 15px;
} #fine-uploader-manual-trigger .buttons {
width: 36%;
} #fine-uploader-manual-trigger .qq-uploader .qq-total-progress-bar-container {
width: 60%;
}
</style> <div id="fine-uploader-manual-trigger"></div>
<div id="BeginQuery" style="margin-top:30px;">
<p><a id="Query" class="btn btn-default">Test File Name</a></p>
</div> </br>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">注意事项</h3>
</div>
<div class="panel-body">
<ul>
<li>文件最大支持<strong>20M</strong></li>
<li>Some other info.</li>
</ul>
</div>
</div> @section Scripts {
<script src="~/fine-uploader/jquery.fine-uploader.js"></script>
<!-- Fine Uploader Thumbnails template w/ customization
====================================================================== -->
<script type="text/template" id="qq-template-manual-trigger">
<div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span class="qq-upload-drop-area-text-selector"></span>
</div>
<div class="buttons">
<div class="qq-upload-button-selector qq-upload-button">
<div>选择文件</div>
</div>
<button type="button" id="trigger-upload" class="btn btn-primary">
<i class="icon-upload icon-white"></i> 上传
</button>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
<li>
<div class="qq-progress-bar-container-selector">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon" aria-label="Edit filename"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
<span class="qq-upload-size-selector qq-upload-size"></span>
<button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
<button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">Delete</button>
<span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul> <dialog class="qq-alert-dialog-selector">
<div class="qq-dialog-message-selector"></div>
<div class="qq-dialog-buttons">
<button type="button" class="qq-cancel-button-selector">Close</button>
</div>
</dialog> <dialog class="qq-confirm-dialog-selector">
<div class="qq-dialog-message-selector"></div>
<div class="qq-dialog-buttons">
<button type="button" class="qq-cancel-button-selector">No</button>
<button type="button" class="qq-ok-button-selector">Yes</button>
</div>
</dialog> <dialog class="qq-prompt-dialog-selector">
<div class="qq-dialog-message-selector"></div>
<input type="text">
<div class="qq-dialog-buttons">
<button type="button" class="qq-cancel-button-selector">Cancel</button>
<button type="button" class="qq-ok-button-selector">Ok</button>
</div>
</dialog>
</div>
</script>
<script>
var filePath;
$('#fine-uploader-manual-trigger').fineUploader({
template: 'qq-template-manual-trigger',
request: {
endpoint: '/Uploader/UploadFile'
},
thumbnails: {
placeholders: {
waitingPath: '/source/placeholders/waiting-generic.png',
notAvailablePath: '/source/placeholders/not_available-generic.png'
}
},
autoUpload: false,
deleteFile: {
enabled: false, // if want to delete, make this true
forceConfirm: true,
endpoint: '/Home/DeleteFile'
},
validation: {
allowedExtensions: ['txt', 'csv'],
itemLimit: 1,
sizeLimit: 51200000 // 50 kB = 50 * 1024 bytes
},
callbacks: {
onComplete: function (id, fileName, responseJSON) {
filePath = responseJSON.extraInformation;
}
}
}); $('#trigger-upload').click(function () {
$('#fine-uploader-manual-trigger').fineUploader('uploadStoredFiles');
}); $('#Query').click(function () {
alert(filePath);
});
</script>
}

Index.cshtml

源代码下载

 

上传组件Fine Uploader在ASP.NET中的应用的更多相关文章

  1. 从零开始编写自己的C#框架(23)——上传组件使用说明

    文章导航 1.前言 2.上传组件功能说明 3.数据库结构 4.上传配置管理 5.上传组件所使用到的类 6.上传组件调用方法 7.效果演示 8.小结 1.前言 本系列所使用的是上传组件是大神July开发 ...

  2. Web Uploader - 功能齐全,完美兼容 IE 的上传组件

    文件上传是网站和 Web 应用程序的常用功能,一直没有一款完美的文件上传组件,因此让很多开发人员碰到头疼的浏览器兼容问题. WebUploader 是由 Baidu FEX 团队开发的一款以 HTML ...

  3. 异步文件上传组件 Uploader

    Uploader是非常强大的异步文件上传组件,支持ajax.iframe.flash三套方案,实现浏览器的全兼容,调用非常简单,内置多套主题支持 和常用插件,比如验证.图片预览.进度条等,广泛应用于淘 ...

  4. ASP.Net大文件上传组件详解

    首先右键单击网站根目录,在弹出的快捷菜单中,选择"添加引用"菜单项,弹出"添加引用",切换到"浏览"找到组件的Dll文件"Best ...

  5. ASP中文件上传组件ASPUpload介绍和使用方法

    [导读]要实现该功能,就要利用一些特制的文件上传组件.文件上传组件网页非常多,这里介绍国际上非常有名的ASPUpload组件 1 下载和安装ASPUpload  要实现该功能,就要利用一些特制的文件上 ...

  6. 前端异步文件上传组件 Uploader

    Uploader是非常强大的异步文件上传组件,支持ajax.iframe.flash三套方案,实现浏览器的全兼容,调用非常简单,内置多套主题支持 和常用插件,比如验证.图片预览.进度条等,广泛应用于淘 ...

  7. ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件

    前言: 从开始学习Vue到使用element-ui-admin已经有将近快两年的时间了,在之前的开发中使用element-ui上传组件el-upload都是直接使用文件选取后立即选择上传,今天刚好做了 ...

  8. ASP.NET MVC 一款可预览、裁剪头像上传组件

    今天介绍一款Web上常用的头像上传组件,常用于头像上传时对用户上传的图片进行裁剪并实时预览,最终效果如下: 源代码结构: Github地址: https://github.com/FrankFan/A ...

  9. 多文件上传组件FineUploader使用心得

    原文 多文件上传组件FineUploader使用心得 做Web开发的童鞋都知道,需要经常从客户端上传文件到服务端,当然,你可以使用<input type="file"/> ...

随机推荐

  1. linux被当矿机排查案例

    1.发现服务器变的特别卡,正常服务运行很慢. 到服务器上查询一番发现top下发现     bashd的进程占用100%CPU了. find /-name bashd* //第一次查询文件占用目录kil ...

  2. PTA 6-1 单链表逆转

    本题是一个非常经典的题目:单链表逆转. 这是链表结点的定义: typedef struct Node *PtrToNode; struct Node { ElementType Data; /* 存储 ...

  3. Quil-delta-enhanced 简介

    Quill 是一款时下非常热门的富文本编辑器,它拥有非常强大的扩展能力,可以让开发者根据自己的需要编写插件,使编辑器支持的内容类型更加丰富.它之所以能够拥有这么强大的扩展能力,一方面是因为它的架构和 ...

  4. C++值多态:传统多态与类型擦除之间

    引言 我有一个显示屏模块: 模块上有一个128*64的单色显示屏,一个单片机(B)控制它显示的内容.单片机的I²C总线通过四边上的排针排母连接到其他单片机(A)上,A给B发送指令,B绘图. B可以向屏 ...

  5. Windows Server 2016 Storage Replication

    Storage Replication是Windows Server 2016中新增的一项功能,它是利用windows server自带的块存储复制技术 首先,我们简答粗暴的交代一下部署需求: 1.该 ...

  6. Xcode 6.3.1Mac版 V6.4.Beta3免费下载

    Xcode for mac是Mac OS系统以及IOS系统开发者专用于构建 Mac OS X 及 iOS 应用程序的完整工具集 - Xcode 5 的工具经过重新设计,它们的性能更优秀.使用更容易,能 ...

  7. python简易的大乐透数据获取及初步分析

    该项目从网上爬取并分析彩票数据,为用户查看和初步分析往期数据提供一种简易的工具. https://github.com/unknowcry/Lottery # -*- coding: utf-8 -* ...

  8. Nginx知多少系列之(七)负载均衡策略

    目录 1.前言 2.安装 3.配置文件详解 4.工作原理 5.Linux下托管.NET Core项目 6.Linux下.NET Core项目负载均衡 7.负载均衡策略 8.加权轮询(round rob ...

  9. vue2.x学习笔记(六)

    接着前面的内容:https://www.cnblogs.com/yanggb/p/12571171.html. class与style绑定 操作元素的class列表和内联样式,是数据绑定的一个常见需求 ...

  10. 5. iphone 的:active样式

    如果给按钮定义 :hover 样式,在 iPhone 上按钮点击一次是 hover 态,再点击一次 hover 态才会消失,这不是我们想要的,继而想通过定义 :active 样式来实现按钮按下时的效果 ...