C# WebAPI 上传文件和图片

4 篇文章 0 订阅
4 篇文章 0 订阅

前端使用 ajax+fromData 方式上传;

直接贴源码:

前台页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        function doUpload() {
            var formData = new FormData($( "#uploadForm" )[0]);
            $.ajax({
                url: 'http://localhost:16516/api/Upload?guid=1234567890' ,
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) {
                    alert(returndata);
                },
                error: function (returndata) {
                    alert(returndata);
                }
            });
        }
    </script>

</head>
<body>
<form id= "uploadForm">
    <p >指定文件名: <input type="text" name="filename" value= ""/></p >
    <p >上传文件: <input type="file" name="file"/></p>
    <input type="button" value="上传" οnclick="doUpload()" />
</form>
</body>

</html>

webapi 后台代码:
 /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="guid">GUID由前端生成</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Upload")]
        public async Task<string> Post(string guid)
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string uploadFolderPath = HostingEnvironment.MapPath("~/Upload");

            //如果路径不存在,创建路径
            if (!Directory.Exists(uploadFolderPath))
                Directory.CreateDirectory(uploadFolderPath);

            List<string> files = new List<string>();
            var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, guid);
            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
              
                foreach (var file in provider.FileData)
                {//接收文件
                    files.Add(Path.GetFileName(file.LocalFileName));
                }
            }
            catch
            {
                throw;
            }
            return string.Join(",", files);
        }

如需多文件上传,GUID请后台生成。

WithExtensionMultipartFormDataStreamProvider 文件说明:


public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public string guid { get; set; }

        public WithExtensionMultipartFormDataStreamProvider(string rootPath,string guidStr)
            : base(rootPath)
        {
            guid = guidStr;
        }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
            return guid + extension;
        }

        private string GetValidFileName(string filePath)
        {
            char[] invalids = System.IO.Path.GetInvalidFileNameChars();
            return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
        }
    }

OK,测试成功!


  • 1
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值