zoukankan      html  css  js  c++  java
  • webApi上传

    /// <summary>
    /// 上传做中转然后后台请求webapi
    /// </summary>
    /// <returns></returns>
    public ActionResult AjaxUploadFiles()
    {
    if (Request.Files.Count > 0)
    {
    try
    {
    var file = Request.Files[0];
    var tempFileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempUploadFile");
    if (!Directory.Exists(tempFileDir))
    {
    Directory.CreateDirectory(tempFileDir);
    }

    string fileFullPath = Path.Combine(tempFileDir, file.FileName);
    //1保存到临时文件夹中
    file.SaveAs(fileFullPath);

    //2代理上传到webAapi
    string url = "http://10.10.0.17:999/api/v1/UploadFile/UploadFiles";
    List<string> fileFullPaths = new List<string>() { fileFullPath };
    ApiReuslt<FileInfoModel> apiReuslt = this.PostUploadFiles(url, fileFullPaths);

    //3.删除本地临时的文件夹
    System.IO.Directory.Delete(tempFileDir, true);
    return Json(apiReuslt, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
    return Json(ApiReuslt<FileInfoModel>.Failed(ex.Message), JsonRequestBehavior.AllowGet);
    }
    }
    return Json(ApiReuslt<FileInfoModel>.Failed("请选择文件"), JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// 代理请求上传到webApi上
    /// </summary>
    /// <param name="baseAddress"></param>
    /// <param name="postUrl"></param>
    /// <param name="fileFulllPaths"></param>
    /// <returns>上传的路径</returns>
    private ApiReuslt<FileInfoModel> PostUploadFiles(string url, List<string> fileFulllPaths)
    {
    using (HttpClient httpClient = new HttpClient())
    {
    using (MultipartFormDataContent content = new MultipartFormDataContent())
    {
    foreach (var filePath in fileFulllPaths)
    {
    var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filePath));
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
    FileName = filePath
    };
    content.Add(fileContent);
    }
    JavaScriptSerializer jss = new JavaScriptSerializer();
    HttpResponseMessage result = httpClient.PostAsync(url, content).Result;
    string json = result.Content.ReadAsStringAsync().Result;
    return jss.Deserialize<ApiReuslt<FileInfoModel>>(json);
    }
    }
    }

  • 相关阅读:
    Express之托管静态文件
    Express与NodeJs创建服务器的两种方法
    NodeJs相关系列文章
    CentOS安装SVN
    图片上传之FileAPI与NodeJs
    Git的基本操作
    页面图片懒加载原理
    JavaScript原生的节点操作
    NodeJs之调试
    CentOS下使用NVM
  • 原文地址:https://www.cnblogs.com/iplaycode/p/10024602.html
Copyright © 2011-2022 走看看