zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    Linux下安装配置词典GoldenDict
    ubuntu 安装LaTex
    ubuntu 安装Opencv2.4.7
    Ubuntu 安装Matlab2010a
    Ubuntu 挂载ISO文件的方法
    ubuntu安装Java jdk1.7.0
    VDI转vmdk(VirtualBox与VMware硬盘格式转换)[转]
    oracle忘记密码,修改密码,解锁
    SQL Server 2008中文企业版下载地址和序列号[转]
    HTTP 错误 500.19 – Internal Server Error web.config 文件的 system.webServer/httpErrors 节中不允许绝对物理路径“C:inetpubcusterr”[转]
  • 原文地址:https://www.cnblogs.com/niuniu0108/p/10081572.html
Copyright © 2011-2022 走看看