webApi上传下载文件

时间:2024-12-13 18:34:32

上传文件通过webApi

html端调用时包含(form提交包含 enctype="multipart/form-data",才可以启作用获取到文件)

public class UploadController : ApiController
{

public async Task<HttpResponseMessage> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

try
{
StringBuilder sb = new StringBuilder(); // Holds the response body

// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);

// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}\n", key, val));
}
}

// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}

}

下载文件通过WebApi

public class DownloadController : ApiController
{
public HttpResponseMessage GetFileFromWebApi()
{
try
{
var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/用户模板.xlsx");
var stream = new FileStream(FilePath, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); //下载所有文件
//response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//下载为Excel
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "用户模板.xlsx"
};
return response;
}
catch
{
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
}