SharePoint 2016 平台 开发FTP的上传下载和删除功能



SharePoint 2016 平台 开发FTP的上传下载和删除功能

先说效果,然后贴出代码:

  • 文件上传,多文件上传


  • 拖拽上传。


上传成功

  • 上传成功查看FTP服务器的文件是否存在。

  • 如果删除,单击前面的多选框然后再选删除就可以了。


  • 下载,要求有文件另存为;

  • 代码如下

using CoreFtp.Infrastructure;
using EBIP.Platform.Core.AuthServer;
using EBIP.Platform.Core.FTP.Application;
using EBIP.Platform.Core.FTP.FTPServer;
using EBIP.Platform.Core.FTP.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using static EBIP.Platform.Core.FTP.Model.MessageResult;


namespace EBIP.Platform.Core.FTP.Controllers
{
    //[Produces("application/x-www-form-urlencoded")]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly OperationServerFile operationServerFile;
        private IHostingEnvironment hostingEnv;
        private readonly FileHelper fileHelper;
        public ValuesController(OperationServerFile operationServerFile, IHostingEnvironment env, FileHelper fileHelper)
        {
            this.operationServerFile = operationServerFile;
            this.hostingEnv = env;
            this.fileHelper = fileHelper;
        }


        [HttpPost("upload")]
        public async Task<IActionResult> PostAsync()
        {
            var files = Request.Form.Files;
            string ftpServerPath = Request.Query["path"].ToString();
            string ftpCode = Request.Query["ftpCode"].ToString();
            string one = ftpServerPath.Substring(0, 1);

            string last = ftpServerPath[ftpServerPath.Length - 1].ToString();
            IList<Datas> data = new List<Datas>();
            var fPServer = this.operationServerFile.FTPServer(ftpCode);
            if (fPServer == null)
            {
                return Json(new MessageResult("upload", 0, "FTP服务器不存在", "1", data));
            }
            var ftpClient = this.operationServerFile.CreateLink(fPServer);
            if (one != "/" || last != "/")
            {

                //return new MessageResult("upload", 0, "上传FTP格式不对,正确为/开始/结束", "1", data);
                return Json(new MessageResult("upload", 0, "上传FTP格式不对,正确为/开始/结束", "1", data));

            }

            var filenametest = "";
            long size = files.Sum(f => f.Length);
            //return Json("1233");
            //size > 100MB refuse upload !
            if (size > fPServer.FTP_FileSize)
            {
                //return new MessageResult("upload", 0, "文件不能>100MB", "1", data);
                return Json(new MessageResult("upload", 0, "文件不能>"+ fPServer.FTP_FileSize + "MB", "1", data));
            }

            List<string> filePathResultList = new List<string>();
            foreach (var file in files)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                 fileName = file.FileName;
                if (fileName.Contains(":\\"))
                {
                    fileName = file.Name;
                }
                if(await operationServerFile.IfFileAsync(ftpClient, ftpServerPath + fileName)==false)
                {
                    return Json(new MessageResult("upload", 0, ""+ fileName + "的文件名已经存在", "1", data));
                  //  break;
                }
            }
            foreach (var file in files)
            {

                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                //string filePath = hostingEnv.WebRootPath + $@"\Files\Files\";
                //string filePath = hostingEnv.ContentRootPath + $@"\Files\Files\";

                //if (!Directory.Exists(filePath))
                //{
                //    Directory.CreateDirectory(filePath);
                //}
                //filenametest = file.FileName;
                //fileName = Guid.NewGuid() + "." + fileName.Split('.')[1] + file.FileName;
               
                //FileStream fileStream = null;
                //file.CopyTo(fileStream);
                //fileStream.Flush();
                //FileStream fileStream = file.OpenReadStream() as FileStream; 
                fileName = file.FileName;
                if (fileName.Contains(":\\"))
                {
                    fileName = file.Name;
                }




                try
                {
                   // string fileFullName = filePath + fileName;
                    //拷贝临时文件到文件夹
                    //using (FileStream fs = System.IO.File.Create(fileFullName))
                    //{
                    //    file.CopyTo(fs);

                    //    fs.Flush();

                    //}
                    filePathResultList.Add($"/src/Files/{fileName}");
                   
                    await operationServerFile.GetUploadAsync(ftpClient, file, ftpServerPath, fileName);
                    var datas = new Datas
                    {
                        fileName = fileName,
                        filePath = ftpServerPath,
                        ftpCode = ftpCode
                    };
                    data.Add(datas);

                   // FileHelper.DeleteFiles(fileFullName, false);
                }
                catch (Exception e)
                {
                    CustomError.Catch(e);
                    throw;
                }

            }
            string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!" + "测试:" + ftpServerPath + "文件名字:" + filenametest;
            //var datas = new Datas
            //{
            //    fileName = endfilenametest,
            //    filePath = ftpServerPath,
            //    ftpCode = ftpCode
            //};
            //return new MessageResult("upload", 1, "上传成功", "1", data);
            var xxx = new MessageResult("upload", 1, "上传成功", "1", data);
            return Json(new MessageResult("upload", 1, "上传成功", "1", data));

            //return Json(Return_Helper_DG.Success_Msg_Data_DCount_HttpCode(message, filePathResultList, filePathResultList.Count));
        }


        [HttpGet("download/{ftpCode}/{ftpServerPath}/{filename}")]
        public async Task<FileContentResult> getDownloadAsync(string ftpCode, string ftpServerPath, string filename)
        {
            IList<Datas> data = new List<Datas>();

            var filenametest = "";


            ftpServerPath = ftpServerPath.Replace('^', '/');

            var fPServer = this.operationServerFile.FTPServer(ftpCode);
            if (fPServer == null)
            {
                //return new MessageResult("download", 0, "FTP服务器不存在", "1", data);
                //return new MessageResult("upload", 0, "FTP服务器不存在", "1", data);
            }
            var ftpClient = this.operationServerFile.CreateLink(fPServer);
            await ftpClient.LoginAsync();

            using (var ftpReadStream = await ftpClient.OpenFileReadStreamAsync(ftpServerPath + filename))
            {
                byte[] fileBytes = ReadToEnd(ftpReadStream);
                //return new MessageResult("download", 0, "FTP服务器不存在", "1", data);
                // string endfilenametest = filenametest.Substring(0, filenametest.Length - 1);
                var datas = new Datas
                {
                    fileName = "xxxx",
                    filePath = ftpServerPath,
                    ftpCode = ftpCode

                };
                //return new MessageResult("download", 1, "下载成功", "1", data);
                return File(fileBytes, "application/force-download", filename);
            }
            //return await operationServerFile.GetDownloadAsync(ftpClient, command.filename, command.ftpServerPath + command.filename);




        }



        //[HttpPost("ifFile")]
        //public async Task IfFileAsync([FromBody]ParameterCommand command)
        //{
        //    await operationServerFile.IfFileAsync(command.userName, command.passWord, command.localDirectory, command.serverDirectory);

        //}

        [HttpPost("deleteFile")]
        public async Task<MessageResult> DeleteFileAsync([FromBody]DeleteFileCommand command)
        {
            IList<Datas> data = new List<Datas>();
            var filenametest = "";
            try
            {

                foreach (string ftpname in command.filnames)
                {
                    var fPServer = this.operationServerFile.FTPServer(command.ftpCode[0]);
                    if (fPServer == null)
                    {
                        return new MessageResult("deleteFile", 0, "FTP服务器不存在", "1", data);
                        //return new MessageResult("upload", 0, "FTP服务器不存在", "1", data);
                    }
                    var ftpClient = this.operationServerFile.CreateLink(fPServer);
                    await operationServerFile.DeleteFileAsync(ftpClient, command.ftpServerPath[0] + ftpname);
                    filenametest += ftpname + ",";
                }

            }
            catch (Exception e)
            {
                CustomError.Catch(e);

            }
            string endfilenametest = filenametest.Substring(0, filenametest.Length - 1);
            var datas = new Datas
            {
                fileName = endfilenametest,
                filePath = command.ftpServerPath[0],
                ftpCode = command.ftpCode[0]
            };
            return new MessageResult("deleteFile", 1, "删除成功", "1", data);

        }

        //[HttpGet("listFilesAsync")]
        //public async Task<IList<FtpNodeInformation>> ListFilesAsync()
        //{
        //    var xxx= await operationServerFile.ListFilesAsync("administrator", "zdhc@123");
        //    return  await operationServerFile.ListFilesAsync("administrator", "zdhc@123");

        //}
        public static byte[] ReadToEnd(System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
    }
}


猜你喜欢

转载自blog.csdn.net/jason_dct/article/details/78676004