• webapi 下载Ftp文件并返回流到浏览器完成文件下载


    ResultModel<HttpResponseMessage> resultModel = new ResultModel<HttpResponseMessage>(ResultStatus.Success);
    FtpWebResponse ftpWebResponse = null;
    Stream ftpStream = null;
    try
    {
    if (dt != null && dt.Rows.Count > 0)
    {
    string content = dt.Rows[0]["Content"].ToString();
    FileSourceDto fileSourceDto = Newtonsoft.Json.JsonConvert.DeserializeObject<FileSourceDto>(content);
    string path = fileSourceDto.TargetInfo.FileUrl.TrimEnd('\').TrimEnd('/') + "/" + fileSourceDto.TargetInfo.FileName;
    string account = fileSourceDto.TargetInfo.UserName;
    string pwd = fileSourceDto.TargetInfo.Password;
    if (!string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(account) && !string.IsNullOrEmpty(pwd))
    {
    FtpWebRequest reqFTP;

    // 根据uri创建FtpWebRequest对象
    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

    // 指定数据传输类型
    reqFTP.UseBinary = true;

    // ftp用户名和密码
    reqFTP.Credentials = new NetworkCredential(account, pwd);
    ftpWebResponse = (FtpWebResponse)reqFTP.GetResponse();
    }

    ftpStream = ftpWebResponse.GetResponseStream();
    byte[] bytes = null;
    using (StreamReader sr = new StreamReader(ftpStream))
    {
    string fileContent = sr.ReadToEnd();
    bytes = Encoding.UTF8.GetBytes(fileContent);
    }
    ftpStream = new MemoryStream(bytes);
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(ftpStream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
    FileName = fileSourceDto.TargetInfo.FileName
    };

    resultModel.Data = response;
    }
    }
    catch (Exception ex)
    {
    resultModel = new ResultModel<HttpResponseMessage>(ResultStatus.Fail, "JD_DataShare_ESB_Error[获取文件流]:" + ex.Message);
    }
    finally
    {
    if (ftpWebResponse != null)
    {
    ftpWebResponse.Close();
    }
    }

    return resultModel;

  • 相关阅读:
    vue+axios拦截器和webapi中读取的实现
    vue+webapi+jwt做token验证时需要注意的一些问题
    vue中引用js文件的方法
    vue+elementui实现表单验证
    vue编程式路由参数的传递
    vue+elementUI实现侧边菜单栏的功能
    vue+webAPI中json相互转换的点滴记录,用于实现按分值的调查问卷功能
    axios中Post请求的两种区别
    vue使用全局变量来定义axios请求地址
    .net Core3.1 webapi前后端一起部署到同一网站遇到的问题
  • 原文地址:https://www.cnblogs.com/niuniu0108/p/10081572.html
Copyright © 2020-2023  润新知