IE可以直接使用img标签
<img src="ftp://account:password@imgurl/xxx.jpg" />
但是谷歌浏览器不支持FTP地址访问,ftp地址会暴露账号密码,存在安全问题。所以可以通过获取图片流的方式来处理。(注意:如果账号或密码有包含特殊字符,可以转义成url编码,如@转义成%40)
后端获取ftp地址图片的数据流,通过File或者base64字符串返回,代码如下:
/// <summary>
/// 返回图片
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public ActionResult FileImage(string url)
{
try
{
FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(url);//创建ftp连接
ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWeb.KeepAlive = false;
ftpWeb.UseBinary = true;
//ftpWeb.UsePassive = false;//如果GetResponse操作超时,可以尝试切换FTP连接模式
ftpWeb.Credentials = new NetworkCredential("username", "password"); // 如果需要身份验证
WebResponse ftpResponse = ftpWeb.GetResponse();
Stream ftpStream = ftpResponse.GetResponseStream();//获取图片流
MemoryStream outstream = new MemoryStream();//转成MS流
int bufferLen = 4096;//缓冲区
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = ftpStream.Read(buffer, 0, bufferLen)) > 0)
{
outstream.Write(buffer, 0, count);
}
return File(outstream.ToArray(), "image/jpeg");//转成图片格式
//return File(outstream.ToArray(), "application/pdf");//转成pdf格式
//return Convert.ToBase64String(outstream.ToArray());//base64字符串
}
catch (Exception ex)
{
return Content("发生错误:" + ex.Message);
}
}
前端img的src地址直接指向Controller,代码如下:
@{
string[] urlArray = model.Split(',');//model为传入页面的多个ftp地址字符串,逗号分隔
for (int index = 0; index < urlArray.Length; index++)
{
<img src="/Image/FileImage?url=@(urlArray[index])" alt="影像图片" style="width:auto;height:auto;padding-bottom:10px;" />
//显示pdf文件的话,用iframe
//如果返回的是base64字符串,则'<iframe src ="data:application/pdf;base64,' + result.Data + '"></iframe>'
}
}