Upload folder of ASP.NET CORE

Keywords: Attribute IE

Recently, I am doing a project of imitating Baidu online disk in my spare time, among which there is a function of uploading folder. It seems that there are few descriptions of this problem on the Internet, so record it here.

1. Find webkitdirectory on the Internet. A new property of H5 is to mark this property on the file control to get all the files in the selected folder.

<input type="file" name="file" webkitdirectory>

Specially looked under Baidu net dish web page version also is uses this attribute, but on the net said that this attribute only Chrome browser supports. Then I don't believe it. I tried it with 360 browser or I can use it. It is found that 360 has two modes (speed mode and compatibility mode). Speed mode is a browsing mode with Blink (Webkit) as the kernel, and chrome seems to use the same kernel. So what I just tried can also be used, but it can't be used when I switch to compatibility mode (IE kernel).

2. Back to the point, just post the code.

<input type="file" name="file" webkitdirectory>
    <button id="upload" type="button" onclick="Upload()" >upload</button>
var files = [];
        $(document).ready(function () {
            $('input').change(function () {
                files = this.files;
            })
        });

        function Upload() {
            var data = new FormData();
            debugger
            for (var i = 0; i < files.length; i++) {
                data.append('file', files[i]);
            }
            var path = files[0].webkitRelativePath;
            $.ajax({
                type: "post",
                url: "/home/UpLoad",
                data: data,
                contentType: false,
                processData: false,
                success: function (data) {
                    console.log(data);
                }
            })
        }

Finally, the controller

[HttpPost]
        public IActionResult UpLoad()
        {
            var files = Request.Form.Files;
            string rootpath = _hostingEnvironment.WebRootPath + @"\Files";

            try
            {
                foreach (var file in files)
                {
                    string[] arrpath = file.FileName.Split(@"/");
                    string dirpath = "";//Directory where the file is located (including one or two levels of directories)
                    string filename = arrpath[arrpath.Length - 1].ToString();//The file name
                    for (int i=0;i<arrpath.Length;i++)
                    {
                        if(i==arrpath.Length-1)
                        {
                            break;
                        }
                        dirpath += arrpath[i]+@"/";
                    }
                    DicCreate(Path.Combine(rootpath, dirpath));//Create the directory if it does not exist

                    
                    string filepath = Path.Combine(rootpath, file.FileName);
                    using (var addFile = new FileStream(filepath, FileMode.OpenOrCreate))
                    {
                        if (file != null)
                        {
                            file.CopyTo(addFile);
                        }
                        else
                        {
                            Request.Body.CopyTo(addFile);
                        }
                        addFile.Close();
                    }
                }

                return Ok(new
                {
                    success = true,
                    message = "Upload success"
                });
            }
            catch(Exception ex)
            {
                return Ok(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// If the file directory does not exist, create a new directory
        /// </summary>
        /// <param name="path"></param>
        private void DicCreate(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

3. Description: the files received by the backend are the collection of all files in the selected folder.

For example, what I test here is to select a folder named new folder, and then there are two pictures and a subfolder in the folder, and the subfolder is also a picture.

All the files I get are the set with count 3. The file names are new folder / 1.jpg, new folder / 2.jpg, new folder / new folder / 8.jpg (this is in the secondary folder).

The general idea is: get the file collection, traverse it, and then get the folder where the file is located. If the folder does not exist on the server, create it and upload the file.

Of course, my code is just the most basic implementation, and there are still some validation or business logic to be analyzed.

Then I won't talk about anything else. If you don't understand the debugging code, you will almost understand it. If you have any errors, please point out.

Source: https://www.cnblogs.com/lyps/p/10303662.html

Posted by KevMull on Fri, 17 Apr 2020 04:52:08 -0700