现如今,世面上流行着许多前端上传组件,例如: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. DataAnalysis-SOP

    一.关于数据分析 a. 互联网最热职位:研发工程师.产品经理.人力资源.市场营销.运营.数据分析(供不应求) b. 数据分析的步骤:明确目的/思路.数据收集.数据处理.数据分析.数据展现 c. 数据分 ...

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

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

  3. for循环,for…in循环,forEach循环的区别

    for循环,for…in循环,forEach循环的区别for循环通关for循环,生成所有的索引下标for(var i = 0 ; i <= arr.length-1 ; i++){ 程序内容 } ...

  4. 让ul li水平居中(任意删除li也能水平居中)

    HTML代码: <div class="box"> <ul class="button-ct"> <li></li&g ...

  5. stand up meeting 12/25/2015 & weekend 12/26/2015~12/27/2015

    part 组员                工作              工作耗时/h 明日计划 工作耗时/h    UI 冯晓云  在pdf阅读页面添加生词本显示:UI美化     6 完善显示 ...

  6. Pet BFS

    一天早上小明醒来时发现他的宠物仓鼠不见了. 他在房间寻找但是没找到仓鼠. 他想用奶酪诱饵去找回仓鼠. 他把奶酪诱饵放在房间并且等待了好几天. 但是可怜的小明除了老鼠和蟑螂没见到任何东西. 他找到学校的 ...

  7. SQL入门,就这么简单

    随着时代的发展,人类活动产生的信息越来越多,大家常说,现在这个时代是大数据时代.在这样一个前提下,数据的存储成为我们必须要认真对待和研究的问题了.SQL(Structured Query Langua ...

  8. Ubuntu上mysql, 通过python连接报错Can't connect to MySQL server on xxx (10061)

    通过sqlyog连接ubuntu上的mysql报错 试了试python直接连接也报同样的错 那应该就是ubuntu上mysql服务自己的问题了 查看mysql 版本 mysql -V root@clo ...

  9. [复现]GXY2019

    前言 当时GXY的时候在复习中,临时抱拂脚,没时间打比赛.就写了一题./(ㄒoㄒ)/~~ babysqli 当时做了写了笔记. 过滤了or,()其中or可以用大小写绕过,可以用order by盲注 第 ...

  10. Asp.Net Core 3.1 学习3、Web Api 中基于JWT的token验证及Swagger使用

    1.初始JWT 1.1.JWT原理 JWT(JSON Web Token)是目前最流行的跨域身份验证解决方案,他的优势就在于服务器不用存token便于分布式开发,给APP提供数据用于前后端分离的项目. ...