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;