• 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);
    }
    }
    }

  • 相关阅读:
    php实现求链表中倒数第k个节点
    在python正在使用mysql
    1002. 写这个号码 (20)(数学啊 ZJU_PAT)
    Lua 环境结构 --Linux
    Java程序猿JavaScript学习笔记(4——关闭/getter/setter)
    C/C++数据对齐汇总
    多线程
    11gRAC CHM 管理
    hdu 4059 The Boss on Mars(纳入和排除)
    模板方法模式分析、图表和基本代码
  • 原文地址:https://www.cnblogs.com/iplaycode/p/10024602.html
Copyright © 2020-2023  润新知