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

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下载地址 https://www.jb51.net/codes/70040.html

2. html代码:

图片上传 - 博客园

$(function () {

$('#jquery-wrapped-fine-uploader').fineUploader({

request: {

endpoint: '/ImageUploader/ProcessUpload'

}

});

});

代码说明:

a)

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

3. 浏览器中的显示效果

4a01ef916a2c3489cc4cc411106eed0a.png

服务器 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 });

}

图片上传结果演示

0831f2f7d1c31f91207ecb12890fa131.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值