美文网首页
c# mvc webapi上传下载

c# mvc webapi上传下载

作者: A_slow_sparrow | 来源:发表于2021-02-04 10:53 被阅读0次
  /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Upload")]
        public async Task<string> Post()
        {

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

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

            string guid = Guid.NewGuid().ToString().Replace("-", "");
            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);
        }
  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('.');
        }

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

  <script>
        function doUpload() {
            var formData = new FormData($("#uploadForm")[0]);
            $.ajax({
            url: '/api/Upload' ,
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) {
            alert(returndata);
                },
                error: function (returndata) {
            alert(returndata);
                }
            });
        }
</script>

相关文章

网友评论

      本文标题:c# mvc webapi上传下载

      本文链接:https://www.haomeiwen.com/subject/difbtltx.html