使用kissy、uploader调用WebApi上传附件

最近在写一个框架,在具体功能实现文档上传的时候,考虑到兼容各种浏览器,以及支持多文件上传,搜索了一些资料,完成简单的DEMO编写,框架为.NET MVC,提供参考。

引用JS下载地址:http://gallery.kissyui.com

uploader JS对图片的上传操作支持度很好,有用到的时候可以去看API。

前台HTML

@{
    ViewBag.Title = "Index";
}
@section scripts{
    <script src="/Content/js/kissy/kissy-1.4.2/build/seed-min.js" type="text/javascript"></script>
    <script>
        var S = KISSY;
        if (S.Config.debug) {
            var srcPath = "/Content/js/kissy/";
            S.config({
                packages: [
                    {
                        name: "gallery",
                        path: srcPath,
                        charset: "utf-8"
                    }
                ]
            });
        }

        S.use('gallery/uploader/1.5.4/index,gallery/uploader/1.5.4/themes/default/index,gallery/uploader/1.5.4/themes/default/style.css', function (S, Uploader, DefaultTheme) {
            //上传组件插件
            var plugins = 'gallery/uploader/1.5.4/plugins/auth/auth,' +
                    'gallery/uploader/1.5.4/plugins/urlsInput/urlsInput,' +
                    'gallery/uploader/1.5.4/plugins/proBars/proBars';

            S.use(plugins, function (S, Auth, UrlsInput, ProBars) {
                var uploader = new Uploader('#J_UploaderBtn', {
                    //处理上传的服务器端脚本路径
                    action: "/api/Upload",
                    //post到服务器的数据
                    data: {
                        Name: "johnson",
                        Price: "200"
                    },
                    multiple: false,//多文件
                    autoUpload :true //自动上传
                });
                //使用主题
                uploader.theme(new DefaultTheme({
                    queueTarget: '#J_UploaderQueue'
                }))
                //验证插件
                uploader.plug(new Auth({
                    //最多上传个数,大小为KB
                    max: 3,
                    maxSize: 1,
                    required: true,
                    allowExts: 'xlsx'
                }))
                         //url保存插件
                        .plug(new UrlsInput({ target: '#J_Urls' }))
                        //进度条集合
                        .plug(new ProBars())
                ;
                uploader.on('add', function (ev) {
                    var file = ev.file;
                    var target = file.target;
                    target.addClass('test');
                });
                uploader.on('success', function (ev) {
                    var index = ev.index, file = ev.file;
                    //服务器端返回的结果集
                    var result = ev.result;
                    S.log('上传成功,服务器端返回url:' + result.url);
                });
                uploader.on('error', function (ev) {
                    var index = ev.index, file = ev.file;
                    //服务器端返回的结果集
                    var result = ev.result;
                    S.log('上传失败,错误消息为:' + result.msg);
                });
            });
        })
</script>
    }
<h2>使用js传参方式上传文件</h2>

<div class="grid">
     <input type="file" class="g-u" id="J_UploaderBtn" value="上传文件" name="Filedata" >
    <input type="hidden" id="J_Urls" name="urls" value="" />
</div>
<ul id="J_UploaderQueue"></ul>
<p>V1.5新增:可以使用label元素来触发文件选择</p>
<div>
    <label for="J_UploaderBtn">触发文件选择</label>
</div>


@*
地址:http://gallery.kissyui.com/uploader/1.5.4/guide/index.html
*@
@*返回格式
{"status":1,"type":"ajax","name":"[1343736002.749366]0.png","url":".\/files\/[1343736002.749366]0.png"}*@
View Code


后台API

namespace UploadTest.Controllers
{
    public class UploadController : ApiController
    {
        public async Task<HttpResponseMessage> PostFormData()
        {
            // Check if the request contains multipart/form-data.
            // 检查该请求是否含有multipart/form-data
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);
            try
            {
                // Read the form data.
                // 读取表单数据
                await Request.Content.ReadAsMultipartAsync(provider);
                //获取传参
                string name = provider.FormData["Name"];
                int price = int.Parse(provider.FormData["Price"]);
                // This illustrates how to get the file names.
                // 以下描述如何获取文件名
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                var resp = new HttpResponseMessage { Content = new StringContent("{\"status\":1}", System.Text.Encoding.UTF8, "text/html") };
                return resp;
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
    }
}
View Code


测试

转载于:https://www.cnblogs.com/strongs/p/3728275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值