SharePoint 2016 platform develops FTP upload, download and delete functions



SharePoint 2016 platform develops FTP upload, download and delete functions

Let's talk about the effect first, then post the code:

  • file upload, multiple file upload


  • Drag and drop to upload.


Uploaded successfully

  • If the upload is successful, check whether the file on the FTP server exists.

  • If you want to delete it, just click the checkbox in front of it and then select Delete.


  • Download, requires a file to be saved as;

  • code show as below

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 server does not exist", "1", data));
            }
            var ftpClient = this.operationServerFile.CreateLink(fPServer);
            if (one != "/" || last != "/")
            {

                //return new MessageResult("upload", 0, "The upload FTP format is incorrect, the correct one is /start/end", "1", data);
                return Json(new MessageResult("upload", 0, "The upload FTP format is incorrect, the correct one is /start/end", "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 + "The file name already exists", "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;
                    //Copy temporary files to the folder
                    //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 dates = new Dates
                    {
                        fileName = fileName,
                        filePath = ftpServerPath,
                        ftpCode = ftpCode
                    };
                    data.Add(data);

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

            }
            string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!" + "测试:" + ftpServerPath + "文件名字:" + filenametest;
            //var dates = new Dates
            //{
            //    fileName = endfilenametest,
            //    filePath = ftpServerPath,
            // ftpCode = ftpCode
            //};
            //return new MessageResult("upload", 1, "上传成功", "1", data);
            var xxx = new MessageResult("upload", 1, "Upload successful", "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 server does not exist", "1", data);
                //return new MessageResult("upload", 0, "FTP server does not exist", "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 server does not exist", "1", data);
                // string endfilenametest = filenametest.Substring(0, filenametest.Length - 1);
                var dates = new Dates
                {
                    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 server does not exist", "1", data);
                        //return new MessageResult("upload", 0, "FTP server does not exist", "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 dates = new Dates
            {
                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;
                }
            }
        }
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325480876&siteId=291194637