[转载]用Fine Uploader+ASP.NET MVC实现ajax文件上传 - dudu - 博客园

[转载][代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 – dudu – 博客园.

Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件的 JavaScript 组件。

This project attempts to achieve a user-friendly file-uploading experience over the web. It’s built as a JavaScript plugin for developers looking to incorporate file-uploading into their website.

Fine Uploader 不依赖于 JQuery,也就是说不引用JQuery.js,也可以正常使用。同时,它也提供了 jQuery Wrapper,可以方便地与jQuery集成。

这篇博文中的示例代码用的就是 Fine Uploader jQuery Wrapper。下面看示例代码:

Web前端实现

1. 下载jQuery Plug-in Fine Uploader,下载地址:https://github.com/valums/file-uploader/wiki/Releases

2. html代码:


图片上传 - 博客园
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script><script type="text/javascript" src="/scripts/jquery.fineuploader-3.0.min.js"></script>
<div id="jquery-wrapped-fine-uploader"></div>
<script type="text/javascript">// <![CDATA[
$(function () {             $('#jquery-wrapped-fine-uploader').fineUploader({                 request: {                     endpoint: '/ImageUploader/ProcessUpload'                 }             });         });
// ]]></script>

代码说明:

a) <div id=”jquery-wrapped-fine-uploader”></div>用于显示上传按钮

b) endpoint 设定的是上传时服务端处理ajax请求的网址。

3. 浏览器中的显示效果

服务器 ASP.NET MVC 实现代码

Fine Uploader 的源代码中用 VB.NET 实现了一个 Controller(UploadController.vb),我们在使用时改为了 C# 代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CNBlogs.Upload.Web.Controllers
{
public class ImageUploaderController : Controller
{
const int ChunkSize = 1024 * 1024;

public ActionResult Upload()
{
return View();
}

public ActionResult ProcessUpload(string qqfile)
{
using (var stream = Request.InputStream)
{
using (var br = new BinaryReader(stream))
{
WriteStream(br, qqfile);
}
}

return Json(new { success = true });
}

private void WriteStream(BinaryReader br, string fileName)
{
byte[] fileContents = new byte[] { };
var buffer = new byte[ChunkSize];

while (br.BaseStream.Position &lt; br.BaseStream.Length - 1) { if (br.Read(buffer, 0, ChunkSize) &gt; 0)
{
fileContents = fileContents.Concat(buffer).ToArray();
}
}

using (var fs = new FileStream(@"C:\\temp\\" + DateTime.Now.ToString("yyyyMMddHHmmSS") +
Path.GetExtension(fileName).ToLower(), FileMode.Create))
{
using (var bw = new BinaryWriter(fs))
{
bw.Write(fileContents);
}
}
}
}
}

图片上传结果演示

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏