zoukankan      html  css  js  c++  java
  • webApi上传下载文件

    上传文件通过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);
    }
    }
    }

  • 相关阅读:
    jquery.validate.js【简单实用的表单验证框架】
    velocity.js实现页面滚动切换效果
    站在巨人的肩膀上——制作酷炫web幻灯片
    简单说说随机打乱数组的方法
    JS数据结构之BinarySearchTree
    做一个extjs的扩展
    【OneAPM】极客编程挑战#025:发挥想象生成漂亮炫酷的SVG动画效果
    将博客搬至CSDN
    练习作品7:批量做字库 识别码
    联系作品6 模版打印 奖状
  • 原文地址:https://www.cnblogs.com/fengziaichou/p/6185739.html
Copyright © 2011-2022 走看看