控制器
/// <summary>
/// 上传文件
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
[Route("/updateDevice")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> FTPUpload(IFormFile files)
{
var file = Request.Form.Files[0];
string fileExt = Path.GetExtension(file.FileName); //取文件后缀名
if (fileExt != ".bin" || file.Length == 0) return Ok("文件格式错误,请重新选择!");
FileTransferHelper.FtpUpLoad(files);
return Ok("上传成功!");
}
///////////////////////////////////上传操作的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Net;
using System.Net.FtpClient;
namespace SFBR.Device.Api.Application.Helper
{
public class FileTransferHelper
{
public static readonly string strServer = ""; //IP地址
public static readonly string strUser = ""; ///用户名
public static readonly string strPassword = "";///密码
public static readonly int port =; ///端口号
public static readonly string filename = ""; ///文件夹
/// <summary>
/// 获取文件名称
/// </summary>
/// <returns></returns>
public string[] RdFileName()
{
try
{
FtpClient ftp = new FtpClient();
ftp.Host = strServer;
ftp.Port = port;
ftp.Credentials = new NetworkCredential(strUser, strPassword);
ftp.Connect();
string[] name = ftp.GetListing(filename).Select(x => x.Name).ToArray();
return name;
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="file"></param>
public async static void FtpUpLoad(IFormFile file)
{
try
{
if (file == null) return;
Stream stream = file.OpenReadStream();
using (FtpClient ftp = new FtpClient())
{
ftp.Host = strServer;
ftp.Port = port;
ftp.Credentials = new NetworkCredential(strUser, strPassword);
ftp.Connect();
string[] str = ftp.GetNameListing();//查询所有文件夹名称
if (!str.Contains($"/{filename}")) //判断是否存在不存在。创建
{
ftp.CreateDirectory($"./{filename}"); //服务器创建文件
}
using (var ftpStrem = ftp.OpenWrite($"/{filename}/{file.FileName}")) //向服务器写入指定文件
{
stream.CopyTo(ftpStrem); //要写入的文件流
}
}
}
catch (Exception e)
{
throw;
}
finally
{
//TODO 释放资源
}
}
}
}