VUE+JAVA 구현zip 파일 코드, 건류

2219 단어 취미

// vue       
 handleModelUpload() {
      alert('  zip  ')
      axios({
        method: 'GET',
        url: '/business/api/download',
        // params: {
        //   // eslint-disable-next-line no-undef
        //   reportRuleId: row.reportRuleId
        // },
        responseType: 'blob'
      }).then(response => {
        const blob = new Blob([response.data], { type: 'application/zip' })
        const url = window.URL.createObjectURL(blob)
        window.location.href = url
      }).catch(error => this.$message.error(error) )
    },




위 그림의 전단method와 같이/bussiness가 내 백엔드를 대리하는 ip의 실제 getMapping 경로는/api/download이다.다음은 백그라운드 자바api입니다.
package com.picchealth.mono.api;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


@RestController
@RequestMapping("/api")
public class DemoApi {


    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        //        
        String filePath = "D://xxx.zip";

        System.out.println("    :" + filePath);

        //     
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("Have no such file!");
            return;
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        //  Http              ,              
        response.setHeader("Content-Disposition", "attachment;Filename=" +
                URLEncoder.encode("xxx.zip", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, len);
        }
        fileInputStream.close();
        outputStream.close();

    }


}


좋은 웹페이지 즐겨찾기