//linux服务器ip
private static string host = Appsettings.app(new string[] { "FTPConfig", "FtpIp" });
//linux服务器登录名
private static string username = Appsettings.app(new string[] { "FTPConfig", "UserName" });
//linux服务器密码
private static string password = Appsettings.app(new string[] { "FTPConfig", "Password" });
//linux服务器文件存放路径
private static string UploadPath = Appsettings.app(new string[] { "FTPConfig", "UploadPath" });
//linux服务器端口
private static int Port = Appsettings.app(new string[] { "FTPConfig", "Port" }).CastToInt32();
/// <summary>
/// 上传文件
/// </summary>
/// <param name="formFile">文件流</param>
/// <param name="Path">分类文件名称</param>
/// <returns></returns>
public static ReultMessage Upload(IFormFile formFile, string Path)
{
Stream stream = null;
try
{
var Extension = Path.GetExtension(formFile.FileName).ToLower();
if (Extension == ".docx" || Extension == ".pdf")
{
var fileName = $"{formFile.FileName.Replace(Extension, "")}【{DateTime.Now.ToString("yyyyMMddhhmmss")}】{Extension}";
var Paths = UploadPath + Path+ "/" + DateTime.Now.ToString("yyyyMM") + "/";
Paths = Path.Combine(Paths);
stream = formFile.OpenReadStream();
var connectionInfo = new Renci.SshNet.ConnectionInfo(host, Port, username, new PasswordAuthenticationMethod(username, password));
using (var sftp = new SftpClient(connectionInfo))
{
sftp.Connect();
if (!sftp.Exists(Paths))
{
sftp.CreateDirectory(Paths);
}
sftp.ChangeDirectory(Paths);
sftp.UploadFile(stream, fileName, true);
sftp.Disconnect();
sftp.Dispose();
}
return new ReultMessage
{
code = 0,
message = "上传成功",
data = (Paths + fileName)
};
}
else
{
return new ReultMessage
{
code = 1,
message = "文件格式不正确"
};
}
}
catch (Exception ex)
{
return new ReultMessage
{
code = 2,
message = ex.Message.ToString()
};
}
finally
{
stream.Close();
stream.Dispose();
}
}
注意:1、需要NuGet包SSH.NET 2、Linux服务器要安装SSH