1:接口代码

/// <summary> /// 文件上传 /// </summary> [HttpPost] 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); List<string> files = new List<string>(); var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, "1234567890"); 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('.'); } }
2:处理跨域问题
引用:System.Web.Http.Cors;
同时要修改 WebApiConfig 文件 添加
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
跨域支持

public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
3:前端调用

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.3.1.min.js"></script> <script src= <script> function doUpload() { var formData = new FormData($( "#uploadForm" )[0]); $.ajax({ url: 'https://localhost:44356/api/Values/Post', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); //alert("asdfasdfds"); } </script> </head> <body> <form id="uploadForm" enctype="multipart/form-data"> <p>指定文件名: <input type="text" name="filename" value="" /></p> <p>上传文件: <input type="file" name="file" /></p> <input type="button" value="上传" onclick="doUpload()" /> </form> </body> </html>