c#实现跨域文件传输具体代码
时间: 2023-07-07 18:18:59 浏览: 194
下面是一份C#实现跨域文件传输的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebApplication1.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class FileController : ApiController
{
[HttpPost]
public HttpResponseMessage UploadFile()
{
HttpResponseMessage response = new HttpResponseMessage();
if (!Request.Content.IsMimeMultipartContent())
{
response.StatusCode = HttpStatusCode.BadRequest;
response.ReasonPhrase = "不支持的媒体类型";
return response;
}
var provider = new MultipartMemoryStreamProvider();
Request.Content.ReadAsMultipartAsync(provider).Wait();
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = file.ReadAsByteArrayAsync().Result;
// 处理上传的文件
var path = HttpContext.Current.Server.MapPath("~/Uploads/" + filename);
File.WriteAllBytes(path, buffer);
}
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent("上传成功");
return response;
}
}
}
```
这是一个ASP.NET Web API控制器,使用了EnableCors特性启用了跨域支持,不限制请求来源、请求头和请求方法。在上传文件时,先判断请求是否为multipart/form-data类型,然后使用MultipartMemoryStreamProvider类将上传的文件读取到内存中,最后将文件保存到指定目录中。上传成功后,返回一个状态码为200的响应和一个上传成功的消息。
阅读全文