Convierta el archivo en un flujo de datos y descargue el archivo

Convierta el archivo en un flujo de datos y descargue el archivo

/**
*将文件按照流的形式读取
*/
public static void writeFileToStream(FileInputStream fileInputStream, OutputStream outputStream, Long size) throws IOException {
    
    
        FileChannel fileChannel = null;
        WritableByteChannel writableByteChannel = null;
        try {
    
    
            fileChannel = fileInputStream.getChannel();
            writableByteChannel = Channels.newChannel(outputStream);
            fileChannel.transferTo(0, size, writableByteChannel);
            outputStream.flush();
        } catch (Exception e) {
    
    

        } finally {
    
    
            fileInputStream.close();
            outputStream.close();
            fileChannel.close();
            writableByteChannel.close();
        }
    }

/**
* 文件下载预览
*/
    @GetMapping(value = "/previewTest/{filename}")
    public void preview(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
    
    
        String filePath = path +filename;//文件的访问路径
        File file = new File(filePath);//对文件进行读取
        FileProcess.writeFileToStream(new FileInputStream(filePath), response.getOutputStream(), file.length());//进行文件流的获取
    }

Supongo que te gusta

Origin blog.csdn.net/qq_46524280/article/details/127359527
Recomendado
Clasificación