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;

  • 相关阅读:
    java中的堆、栈、常量池
    java中int和Integer的区别
    python linecache模块读取文件的方法
    Python 字符串中 startswith()方法
    Python中的filter()函数的用法
    python sort、sorted高级排序技巧
    二级指针内存模型(一)
    Linux下多线程模拟停车场停车
    linux线程操作
    C语言实现多线程排序
  • 原文地址:https://www.cnblogs.com/niuniu0108/p/10081572.html
Copyright © 2011-2022 走看看