'Corrupted File from Uploading Bytes for Large Attachment Graph API
I'm using the Microsoft Graph API to upload a large file to a message. After uploading all the bytes of the file, the size of the uploaded file looks correct, but it's always corrupted (if I open the file, it will say it's been corrupted and can't be read).
What might I be doing wrong here?
$attachment[] = [
"contentBytes" => $someFileAttachment->getContentBytes(),
'attachment' => [
'AttachmentItem' =>
new FileAttachment(
[
"attachmentType" => "file",
"name" => $someFileAttachment->getName(),
"size" => $someFileAttachment->getSize()
]
)
]
];
// upload the file to the draft message
$uploadSessionResult = $createUploadSession($attachment['attachment'], $draftMessageId, $emailAddress);
$fragSize = 320 * 1024;
$fileSize = $attachment['attachment']['AttachmentItem']->getSize();
$numFragments = ceil($fileSize / $fragSize);
$bytesRemaining = $fileSize;
$i = 0;
while ($i < $numFragments) {
$chunkSize = $numBytes = $fragSize;
$start = $i * $fragSize;
$end = $i * $fragSize + $chunkSize - 1;
$offset = $i * $fragSize;
if ($bytesRemaining < $chunkSize) {
$chunkSize = $numBytes = $bytesRemaining;
$end = $fileSize - 1;
}
$stream = fopen('php://temp', 'r+');
fwrite($stream, $attachment['contentBytes']);
rewind($stream);
$data = stream_get_contents($stream, $chunkSize, $offset);
fclose($stream);
$contentRange = "bytes " . $start . "-" . $end . "/" . $fileSize;
$uploadBytes($uploadSessionResult->getUploadUrl(), $numBytes, $contentRange, $data);
$i++;
$bytesRemaining = $bytesRemaining - $chunkSize;
}
Solution 1:[1]
I had some similar issue before and this was the soloution for me. I hope it helps you too.
after:
$data = stream_get_contents($stream, $chunkSize, $offset);
add:
$data= pack("H" . strlen($data), $data);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
