jquery ajax 上传文件

本文介绍如何在ASP.NET中使用C#处理客户端上传的文件,并通过AJAX实现异步文件上传。代码示例展示了从获取文件集合、判断文件存在、获取扩展名到保存文件的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html
            //获取客户端上传的文件集合
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //相对路径
            string path = "";
            //判断文件是否存在
            if (files.Count > 0) {
                //获取扩展名
                string extension = Path.GetExtension(files[0].FileName);
                if (!string.IsNullOrEmpty(extension))
                {
                    path = "/Content/images/" + Guid.NewGuid() + extension;
                    //获取文件集合中的第一个文件(每次只上传一个文件)
                    HttpPostedFile file = files[0];
                    string fullpath = System.Web.HttpContext.Current.Server.MapPath(path);
                    file.SaveAs(fullpath);
                }
            }
后台代码
     $.ajaxFileUpload({
            url: '/MarketingStrategyModule/MarketingStrategy/SaveMarketingBookForm?keyValue=' + keyValue,
            data: {
                name: entity.name, rule_rights: entity.rule_rights,
                state: entity.state, is_member: entity.is_member, start_date: entity.start_date,
                end_date: entity.end_date, dsc: entity.dsc, terminal: entity.terminal, members: entity.members,
                products: entity.products.replace(new RegExp('"', "gm"), "'")  //entity.products是一个数组,需要先转成JSON后,再进行正则替换,否则后台接受到的是“【{”
            },
            type: "POST",
            fileElementId: 'uploadFile',
            dataType: 'json',
            success: function (data) {
                bpm.loading(false);
                if (data.code == 200) {
                    //保存成功后才回调
                    if (!!callBack) {
                        callBack();
                    }
                    bpm.alert.success('保存成功');
                    bpm.layerClose(window.name);
                } else {
                    bpm.alert.warning(data.info);
                }
            }
        });
View Code

 

转载于:https://www.cnblogs.com/xielideboke/p/11136641.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值