.netcore+vue 압축 파일 다운로드 기능 구현

하나.앞말
현재 접촉한 프로젝트에서 주어진 수요는 시스템 내의 모든 사용자의 데이터를 정리하고 폴더에 저장하는 것이다. 그 목적은 주로 사용자가 실시 인원이 이미 설정한 토대에서 시스템에 익숙하지 않아 발생하는 삭제나 오작동을 방지하는 것이다.구현 인원의 구성 작업을 줄이다.내가 가장 먼저 생각한 것은 데이터를 Excel로 가져오고 각 사용자의 이름으로 폴더를 분류하는 것이다.
vue에서 Excel 가져오기를 실현하는 것은 우리가 본 것이 비교적 많았다. 당시에 나도 Excel을 다운로드하는 기능을 실현했다. 그러나 다음에 저장된 파일이 서버에 있다는 것을 발견했다. 그러면 문제가 하나 있다. 실시자는 페이지를 통해 클릭한 클릭으로 저장 단추를 눌렀고 데이터도 확실히 저장했지만 서버에 있었다. 만약에 실시간으로 데이터를 보고 싶다면 서버에 가서 한 부를 복사해야 하지 않겠는가.상대적으로 번거롭기 때문에 압축 파일을 로컬로 다운로드하는 기능을 정리하고 어떻게 실현되었는지 함께 봅시다.
1.1.net core 압축 파일
사고방식은 백엔드에서 폴더 전체를 zip 형식의 압축 패키지로 압축하고 파일을 백엔드로 되돌린 다음에 백엔드에서 파일 흐름을 수신하여 브라우저 다운로드 기능을 실현하는 것이다.
백엔드 코드,

public async Task<FileStreamResult> DownloadFiles(DownLoadModel input)
    {
      if (!Directory.Exists(input.pathUrl))
      {
        throw new UserFriendlyException(" ");
      }
      var zipFileUrl = _configurationRoot["downLoadUrlConf:downloadZipFileUrl"];
      if (File.Exists(zipFileUrl))
      {
        File.Delete(zipFileUrl);
      }
      ZipHelper.CreateZip(input.pathUrl, zipFileUrl);
      var memoryStream = new MemoryStream();
      using (var stream = new FileStream(zipFileUrl, FileMode.Open))
      {
        await stream.CopyToAsync(memoryStream);
      }
      memoryStream.Seek(0, SeekOrigin.Begin);
      return new FileStreamResult(memoryStream, "application/octet-stream");// , ContenType。
    }

 public static class ZipHelper
  {
    /// <summary>
    ///  
    /// </summary>
    /// <param name="sourceFilePath"></param>
    /// <param name="destinationZipFilePath"></param>
    public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
    {
      if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
        sourceFilePath += System.IO.Path.DirectorySeparatorChar;

      ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
      zipStream.SetLevel(6); //   0-9
      CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);

      zipStream.Finish();
      zipStream.Close();
    }
    /// <summary>
    ///  
    /// </summary>
    /// <param name="sourceFilePath"> </param>
    /// <param name="zipStream">
    /// <param name="staticFile"></param>
    private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
    {
      Crc32 crc = new Crc32();
      string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
      foreach (string file in filesArray)
      {
        if (Directory.Exists(file))           // , 
        {
          CreateZipFiles(file, zipStream, staticFile);
        }

        else                      // , 
        {
          FileStream fileStream = File.OpenRead(file);

          byte[] buffer = new byte[fileStream.Length];
          fileStream.Read(buffer, 0, buffer.Length);
          string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
          ZipEntry entry = new ZipEntry(tempFile);

          entry.DateTime = DateTime.Now;
          entry.Size = fileStream.Length;
          fileStream.Close();
          crc.Reset();
          crc.Update(buffer);
          entry.Crc = crc.Value;
          zipStream.PutNextEntry(entry);

          zipStream.Write(buffer, 0, buffer.Length);
        }
      }
    }
  }
그 중에서 CreateZip 방법은 원본 파일의 경로, 목표 파일의 경로를 전송합니다. 여기서 제 목표 파일은 appsetting에 설정되어 있습니다.json은 임시 경로로 앞부분만 다운로드할 수 있습니다.이렇게 하면 우리는 백그라운드에서 데이터를 압축 패키지 형식으로 압축하고 데이터가 전방으로 흐르도록 되돌려준다.
1.2 vue 압축 파일 다운로드

 <el-button
     icon="el-icon-download"
     size="mini"
     type="primary"
     class="pull-right"
     @click="downloadFile"
    > </el-button>

 downloadFile() {
    this.loading = true;
    let postData = { pathUrl: this.filePathMag };
    AjaxHelper.post(this.downLoadUrl, postData, {
     responseType: "blob",
    }).then((res) => {
     //  
     const content = res.data;
     const blob = new Blob([content], { type: "application/zip" });
     const fileName = this.tenant.name + " .zip";
     if ("download" in document.createElement("a")) {
      //  IE 
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); //  URL  
      document.body.removeChild(elink);
     } else {
      // IE10+ 
      navigator.msSaveBlob(blob, fileName);
     }
     this.loading = false;
    });
   },
이전에 Excel을 다운로드할 때 백엔드에 전송된 콘텐츠-type은'application/json; application/octet-stream'입니다. 테스트를 통해 압축 파일은 이런 콘텐츠-type을 사용할 수 없다는 것을 발견하여 삭제했습니다.
또한constblob=newblob([content], {type:"application/zip"});이 줄 코드는 추가하지 않으면 다운로드할 수 있지만 다운로드한 압축 패키지는 열 수 없습니다. 압축이 정확하지 않거나 압축 패키지가 손상되었음을 알립니다.
자, 이 압축 파일의 다운로드는 완성되었습니다. 저도 처음으로 압축 파일의 다운로드를 만났기 때문에 모색 끝에 문제를 해결했습니다.보기에도 비교적 간단해 보이는데, 너는 사용하는 것을 배웠니?
총결산
이것에 관하여netcore+vue 압축 파일 다운로드를 실현하는 글은 여기에 소개되었습니다. 더 많은 관련 vue 압축 파일 다운로드 내용은 저희 이전의 글을 검색하거나 아래의 관련 글을 계속 찾아보세요. 앞으로 많은 응원 부탁드립니다!

좋은 웹페이지 즐겨찾기