欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]

程序员文章站 2024-03-04 19:08:06
this project attempts to achieve a user-friendly file-uploading experience over the we...
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
fine uploader下载地址
2. html代码:
复制代码 代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>图片上传 - 博客园</title>
<link href="/css/fineuploader.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="/scripts/jquery.fineuploader-3.0.min.js"></script>
</head>
<body>
<div id="jquery-wrapped-fine-uploader"></div>
<script>
$(function () {
$('#jquery-wrapped-fine-uploader').fineuploader({
request: {
endpoint: '/imageuploader/processupload'
}
});
});
</script>
</body>
</html>

代码说明:
a) <div id="jquery-wrapped-fine-uploader"></div>用于显示上传按钮
b) endpoint 设定的是上传时服务端处理ajax请求的网址。
3. 浏览器中的显示效果

用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]


服务器 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 < br.basestream.length - 1)
{
if (br.read(buffer, 0, chunksize) > 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);
}
}
}
}
}

服务器端实现改进版
复制代码 代码如下:

public actionresult processupload(string qqfile)
{
using (var inputstream = request.inputstream)
{
using (var fliestream = new filestream(@"c:\temp\" + qqfile, filemode.create))
{
inputstream.copyto(fliestream);
}
}
return json(new { success = true });
}

图片上传结果演示

用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]