FTP跨服务器上传图片--FtpWeb类
1、创建FtpWeb.cs 文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
namespace DeYangService
{
public class FtpWeb
{
string ftpServerIP;
string ftpRemotePath;
string ftpUserID;
string ftpPassword;
string ftpURI;
/// <summary>
/// 连接FTP
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
private static bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
{
bool flag = true;
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception)
{
flag = false;
}
return flag;
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="httpfile">需要上传的文件</param>
/// <param name="targetDir">目标路径</param>
/// <param name="ext">文件类型</param>
/// <param name="hostname">ftp地址</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
/// <param name="ismakethumbnail">是否需要截图</param>
/// <param name="isappmakethumbnail">是否需要截成app图</param>
/// <summary>
public static void UploadFile(HttpPostedFile httpfile, string targetDir, string ext,string hostname, string username, string password,bool ismakethumbnail,bool isappmakethumbnail)
{
string URI = "FTP://" + hostname + "/" + targetDir+ ext;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
//设置FTP命令 设置所要执行的FTP命令,
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
//指定文件传输的数据类型
ftp.UseBinary = true;
ftp.UsePassive = true;
//告诉ftp文件大小
ftp.ContentLength = httpfile.ContentLength;
//缓冲大小设置为2KB 1M
const int BufferSize = 10240;
byte[] content = new byte[BufferSize - 1 + 1];
int dataRead;
//打开一个文件流 (System.IO.FileStream) 去读上传的文件
using (Stream fs = httpfile.InputStream)
{
//把上传的文件写入流
using (Stream rs = ftp.GetRequestStream())
{
do
{
//每次读文件流的2KB
dataRead = fs.Read(content, 0, BufferSize);
rs.Write(content, 0, dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
}
#region 截图
if (ismakethumbnail)
{
//小图 120*120
byte[] datamin = ThumbnailImage.MakeThumbnail(fs);
MemoryStream m = new MemoryStream(datamin);
UploadThumbnail(m, targetDir + "min", ext, hostname, username, password);
m.Close();
中图 240*180
byte[] datamid = ThumbnailImage.MakeImage(fs, 240, 180);
m = new MemoryStream(datamid);
UploadThumbnail(m, targetDir + "mid", ext, hostname, username, password);
m.Close();
}
if (isappmakethumbnail)
{
手机适配的尺寸 1张图:400*100 多张图时:100*80
byte[] dataAppmid = ThumbnailImage.MakeImage(fs, 400, 100);
MemoryStream m = new MemoryStream(dataAppmid);
UploadThumbnail(m, targetDir + "appmid", ext, hostname, username, password);
m.Close();
手机适配的尺寸 1张图:400*100 多张图时:100*80
byte[] dataAppmin = ThumbnailImage.MakeImage(fs, 100, 80);
m = new MemoryStream(dataAppmin);
UploadThumbnail(m, targetDir + "appmin", ext, hostname, username, password);
m.Close();
}
#endregion 截图
fs.Close();
}
}
/// <summary>
/// 上传缩略图
/// </summary>
/// <param name="httpfile">需要上传的文件</param>
/// <param name="targetDir">目标路径</param>
/// <param name="ext">文件类型</param>
/// <param name="hostname"> ftp地址</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
public static void UploadThumbnail(MemoryStream m, string targetDir, string ext, string hostname, string username, string password)
{
string URI = "FTP://" + hostname + "/" + targetDir + ext;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
//设置FTP命令 设置所要执行的FTP命令,
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
//指定文件传输的数据类型
ftp.UseBinary = true;
ftp.UsePassive = true;
//告诉ftp文件大小
ftp.ContentLength = m.Length;
//缓冲大小设置为2KB 1M
const int BufferSize = 10240;
byte[] content = new byte[BufferSize - 1 + 1];
int dataRead;
//把上传的文件写入流
using (Stream rs = ftp.GetRequestStream())
{
do
{
//每次读文件流的2KB
dataRead = m.Read(content, 0, BufferSize);
rs.Write(content, 0, dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
}
m.Close();
}
/// <summary>
/// 得到ftp对象
/// </summary>
/// <param name="URI">ftp地址</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
/// <returns>返回ftp对象</returns>
private static System.Net.FtpWebRequest GetRequest(string URI, string username, string password)
{
//根据服务器信息FtpWebRequest创建类的对象
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
//提供身份验证信息
result.Credentials = new System.Net.NetworkCredential(username, password);
//result.Credentials = new System.Net.NetworkCredential();
//设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
result.KeepAlive = false;
return result;
}
}
}
2、配置web.config 文件
<!--fpt 服务器用户名及账户及主机地址-->
<add key="HOSTNAME" value="192.168.0.190"/>
<add key="USER_NAME" value="lenovo"/>
<add key="PASSWORD" value="123456"/>
3、调用方法上传图片文件至图片服务器
注释:多张图片上传过程。
string fexts = "";
string filepaths = ""; //file1,file2,file3
//已上传图片
if (context.Request.Files.Count > 0)
{
int fcount = context.Request.Files.Count;
for (int i = 0; i < fcount; i++)
{
string newpath = CloudTool.GetSavePath();// imgSavePath.GetPerImgSavePath(uid);
string code = DateTime.Now.ToString("yyyyMMddhhmmssff");
string[] fileNameArray = context.Request.Files[i].FileName.Split(new char[] { '/' });
string fileName = System.IO.Path.GetFileName(context.Request.Files[i].FileName);
string ext = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
string sourpath = newpath + code + ext;//fileNameArray[fileNameArray.Length - 1];
string minpath = newpath + code + "min" + ext;
string midpath = newpath + code + "mid" + ext;
string Appmidpath = newpath + code + "appmid" + ext;
string Appminpath = newpath + code + "appmin" + ext;
txtareas += "图片";
string filepath = newpath + code;
filepaths += filepath.Substring(3).Replace("\\", "\\\\");//保存文件路径
filepath = filepath + ext;
fexts += ext;
if (i < context.Request.Files.Count - 1)
{
filepaths += "`";
fexts += "`";
txtareas += "`";
}
#region 保存到图片服务器
//1)图片服务器配置信息 ip、账户、密码
string hostname = CloudTool.GetAppSettingByKey("HOSTNAME");
string username = CloudTool.GetAppSettingByKey("USER_NAME");
string password = CloudTool.GetAppSettingByKey("PASSWORD");
//2)设置图片文件的名称及存放地址
DateTime dttime = DateTime.Now;
string year = dttime.Year.ToString();
string month = dttime.Month.ToString();
string day = dttime.Day.ToString();
string hour = dttime.Hour.ToString();
var folder = year + "\\" + month + "\\" + day + "\\" + hour + "\\";
string dirName = folder + code;
FtpWeb ftpweb1 = new FtpWeb(hostname, "", username, password);
//3)创建文件夹目录
ftpweb1.MakeDir(folder);
//4)上传图片
FtpWeb.UploadFile(context.Request.Files[i], dirName, ext, hostname, username, password, true,true);
#endregion
}
}
bool flag = false;
//将图片地址保存到数据库 --自己编写
//flag = zkDAL.createzkimg(nid, uid, txtname, zkey, typeid, zflag, txtcontent, txtauthor, filepaths, fexts, txtareas, tagkeys);