下载接口同时返回文件和数据

后端接口

import com.example.wxservice.dto.FileDto;
import com.example.wxservice.service.FileService;
import com.example.wxservice.test.ftpfileload.SFTPUtil;
import com.example.wxservice.util.R;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(String id) throws IOException {
        FileDto fileDto = fileService.getById(id);
        File file = new File(fileDto.getFilePath());
        byte[] data = Files.readAllBytes(file.toPath());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file.getName());
        headers.setContentLength(data.length);
        headers.setAccessControlExposeHeaders(Arrays.asList("result"));
        headers.set("result", "222");
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }

前端

download(file) {
  axios({
    url: base.fileDownload + '?id=' + file.id,
    method: 'GET',
    responseType: 'blob' // 表示接收二进制数据
  })
    .then(response => {
      console.log(JSON.stringify(response.headers.get("result")))
      let blob = new Blob([response.data]);
      let fileName = file.fileName;
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        //释放内存
        window.URL.revokeObjectURL(link.href);
      }
    })
    .catch(error => {
      console.error(error)
    })
}

你可能感兴趣的:(java,spring,前端)