c# mvc webapi上传下载

  /// <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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容