SoFunction
Updated on 2025-04-04

vue implements the operation of uploading the page folder and compressing it to the server.

vue implements page upload folder compression and then pass it to the server

Requirements: Click the page button to upload the folder, but it needs to be compressed through the front end before uploading it to the server (as for why you don’t first set up the compression package and then upload it directly, the leader means that the file he wants to upload is encrypted locally, and the file uploaded to the browser is decrypted. I don’t understand it very much, but the requirements still have to be completed)

1. First download the required plugins jszip and FileSaver

npm install jszip
npm install file-saver  // It is mainly used to download files to verify whether the upload is correct, not just needed//Page introductionimport JSZip from "jszip";
import FileSaver from "file-saver";

2. For page tags, only one button is needed.

<el-form-item label="Upload template:" prop="fileName">
            <el-button @click="handleChange">Upload folder</el-button>
</el-form-item>

3. Complete code

  handleChange() {
    let input = ("input");
     = "file";
    ("allowdirs", "true");
    ("directory", "true");
    ("webkitdirectory", "true"); //If you set up the webkitdirectory, you can select a folder for uploading. el-upload is also applicable but the methods are different     = false;
    ("body").appendChild(input);
    ();
    let _this = this;
     = async function (e) {
      let file = ["files"];
      let path = file[0].webkitRelativePath; //Get path to get the name of the uploaded folder level      let name = ("/")[0];
      (name);
      let zip = new JSZip();
      _this.forEachZip(zip, file); // Process all subfiles in the folder      // Generate compressed files      ({ type: "blob" }).then((content) => {
      //Convert blob type to file type for upload        let zipFile = new File([content], `${name}.zip`, {
          type: "application/zip",
        });
        // Make a size limit        let isLt2M =  / 1024 / 1024 < 80;
        if (!isLt2M) {
          _this.fileList = [];
          _this.$message({
            message: "The uploaded file size cannot exceed 80MB!",
            type: "warning",
          });
          return false;
        } else {
           let filedata = new FormData();
           ("file", zipFile);
          _this.handlesubmit(filedata); //This place can be replaced with its own upload event, filedata is already a compressed file          // (content, `${name}.zip`); //For download, you can download the file to see if the upload is correct        }
      });
      ("body").removeChild(input);
    };
  },
  forEachZip(zip, files) {
    for (let i = 0; i < ; i++) {
    //Classify and process all sub-files in the folder through path, mainly to keep the uploaded folder directory unchanged      (files[i].webkitRelativePath, files[i]);
      //If you want to classify all folders in it to level one after uploading, you can use the following method       // let file = files[i];
      // (, file);
    }
  },

Vue project uses jszip and file-saver to package and compress upload folders

Installation package

npm install jszip
npm install file-saver

Introduce package

import { saveAs } from 'file-saver'
import JSZip from 'jszip'

1. Set input upload file

<input type="file" webkitdirectory="true" directory="true" @click="onupclick" @change="uploadFiles" style="width: 70px" />

2. When we have uploaded, we must refresh the page before we can continue to upload. We only need to set the following and upload it again

function onupclick(e: any) {
	 = 0;//Upload progress, you can use the element plus progress bar component	 = null;
	 = '';
}

3. Set up the upload function

async function uploadFiles(e) {
	let res = await zipFile(2, );
	const file = new File([res], '');//'' is the set file name	upzip({ ftype: 1, file: file, mode:  });
}
async function zipFile(index: number, fileList: FileList, onProgress: (added: number) =&gt; void) {
	const zip = new JSZip();
	let i = 0;
	for await (let f of fileList) {
		const fileData = await readAsArrayBuffer(f);
		(, fileData, { createFolders: true });
		i++;
		onProgress &amp;&amp; onProgress(i);
	}
	return ({ type: 'blob', compression: 'DEFLATE', compressionOptions: { level: 9 } }, function updateCallback(metadata) {
		// Progress bar			 = +(2);
		// ('Progress bar', (2) + '% done');	});
 //({ type: 'blob' })
        //    .then(function (zipBlob) {
                // You can perform upload operations here and send zipBlob to the server                // You can also save the ZIP file locally by             // (zipBlob, 'zip package name.zip');            // })
             //.catch(function (error) {
            // ('Compressed video failed:', error);            // });
}
async function readAsArrayBuffer(file: Blob): Promise&lt;ArrayBuffer&gt; {
	return new Promise((resolve, reject) =&gt; {
		let reader = new FileReader();
		(file);
		 = () =&gt; {
			resolve( as ArrayBuffer);
		};
		 = () =&gt; {
			reject('FileReader failed');
		};
	});
}
//Upload the file to the serverasync function upzip(formData: any) {
	try {
		const { code, msg } = await upload_file(formData);
		if (code &gt; 0) {
			ElMessage({
				showClose: true,
				message: 'Uploaded successfully',
				type: 'success',
			});
		} else {
			ElMessage({
				showClose: true,
				message: 'Upload failed' + msg,
				type: 'error',
				duration: 0,
			});
		}
	} catch (e) {
		ElMessage({
			showClose: true,
			message: 'mistake: ' + e,
			type: 'error',
			duration: 0,
		});
	}
}

This is the article about uploading folders to the server after the vue implementation page is introduced. For more related contents of upload folders to the server, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!