使用图形 API Java 代码从 SharePoint 下载后面临文件损坏(Excel)的问题

问题描述 投票:0回答:1

我正在尝试从共享点下载 Excel 文件。我可以从 SharePoint 应用程序将该文件下载到我的本地系统中。但是,当我尝试打开下载的 Excel 文件时,它说文件已损坏,无法打开该文件。下载时文件大小也会增加。 我正在使用如下代码。

// Fetch file content as InputStream

InputStream inputStream = graphClient
                .sites(siteId)
                .drives(driveId)
                .root()
                .itemWithPath(filePath)
                .content()
                .buildRequest()
                .get();

if (inputStream == null) {
    throw new Exception("Failed to fetch file content from SharePoint.");
}

// Read InputStream into byte array
byte[] fileBytes = inputStream.readAllBytes();
logger.info("Downloaded " + fileBytes.length + " bytes.");

// Save the byte array as a file
Path destinationPath = Paths.get(localFilePath);
try (FileOutputStream fos = new FileOutputStream(destinationPath.toFile())) {
    fos.write(fileBytes);
    logger.info("File saved to " + localFilePath);
} catch (IOException e) {
    logger.severe("Error saving the file: " + e.getMessage());
    throw e;
}

我也尝试过像belwo代码这样的字节。

try {
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadPath.toFile()));
    //FileOutputStream outputStream = new FileOutputStream(downloadPath.toFile());
    byte[] buffer = new byte[16 * 1024]; // Buffer size (8 KB)
    int bytesRead;

    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
        totalBytesRead += bytesRead;
    }

    outputStream.flush();
    logger.info("File downloaded successfully to: " + downloadPath.toString());

} catch (IOException e) {
    logger.error("Error while saving the file to disk: " + e.getMessage(), e);
}

请帮我解决这个问题,是否有其他方法可以下载该文件。主要问题是我无法打开 excel 和 pdf 等文件。

我也尝试过下面的代码

try {
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(downloadPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadPath.toFile()));
    byte[] dataBuffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = bis.read(dataBuffer, 0, 1024)) != -1) {
        bos.write(dataBuffer, 0, bytesRead);
    }

    outputStream.flush();
    logger.info("File downloaded successfully to: " + downloadPath.toString());
} catch (IOException e) {
    logger.error("Error while saving the file to disk: " + e.getMessage(), e);
}
java microsoft-graph-api
1个回答
0
投票

不要自己实现,其他人已经为你完成了;-)

尝试使用 Apache Commons IO 并使用方法

IOUtils.copy(InputStream, OutputStream)
IOUtils.copyLarge(InputStream, OutputStream)

如果您想调整其大小,您甚至可以使用该方法的变体,在其中可以指定自己的复制缓冲区。

© www.soinside.com 2019 - 2024. All rights reserved.