专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

.net6+ajax上传图片

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:21:18       共计:3734 浏览

html


文件名:<input type="text" name="filename" />
文件: <input type="file" name="my_file" />


ajax

UploadImg:function(){
                    var formData = new FormData($("#form_avatar")[0]);
                    $.ajax({
                        url: "/Privacy/UploadUserImg",
                        type: "POST",
                        headers: { "Authorization": 'Bearer ' + token },
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (data) {
                            console.log(data);
                            if(data.success){
                                $('#head-view').attr('src',data.response);
                            }
                        },
                        error: function (e) {
                            console.log("系统出错!");
                            console.log(e.error);
                        }
                    });
                }



  MVC后端     

        /// <summary>

        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UploadFile()
        {
            #region Api处理模块
            try
            {
                //获取上传文件
                IFormFileCollection files = HttpContext.Request.Form.Files;
                //判断是否有文件上传
                if (files.Count == 0)
                {
                    return new HttpResponseMessage(HttpStatusCode.BadRequest);
                }
               


                for (int i = 0; i < files.Count; i++)
                {
                    //设置文件上传路径
                    string fileHead = $"/FileUpload/{DateTime.Now:yyyyMMdd}";
                    string fullFileName = string.Format("{0}/{1}", fileHead, Path.GetFileName(files[i].FileName));
                    ////创建文件夹,保存文件
                    string path = Path.GetDirectoryName(fullFileName);
                    #region 检查上传的物理路径是否存在,不存在则创建
                    //获取当前项目所在的物流路径
                     path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase+ path;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    #endregion
                    //保存文件  文件存在则先删除原来的文件
                    if (System.IO.File.Exists(fullFileName))
                    {
                        System.IO.File.Delete(fullFileName);
                    }
                    //将流写入文件
                    using (Stream stream = files[i].OpenReadStream())
                    {
                        // 把 Stream 转换成 byte[]
                        byte[] bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, bytes.Length);
                        // 设置当前流的位置为流的开始
                        stream.Seek(0, SeekOrigin.Begin);
                        // 把 byte[] 写入文件
                        FileStream fs = new FileStream(path+$"/{DateTime.Now:yyyyMMddHHmm}{Path.GetExtension(files[i].FileName)}", FileMode.Create);
                        BinaryWriter bw = new BinaryWriter(fs);
                        bw.Write(bytes);
                        bw.Close();
                        fs.Close();
                    }


                }
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
            #endregion
        }
版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:asp.net MVC上传图片 | ·下一条:C#中Path.xxxx 文件路径,文件名,文件扩展名处理

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有