I'm using the Microsoft Graph API to get the contents of a file, but something is off about the encoding with the content bytes being returned. When I view the file in Notepad++, the contents look something like this:
UÏMÌ؈€aX!D"AŠMtPïq¡ª†f24O]J¦¢’k¿ÇFcX+|¿¯÷q”z{CîËC~ãZVŸâÆù ´*ëáµå:ã/•þ57Yü*—kØ&Ž=NDüßÒLó>#÷.MÊ
×núšÙÄlsb´Ò·SFAÙá~˜ wpÌ&—wY¯ÇpÊúé(¯uïû°×Œ†ˆ÷.”ÒB1ŒKŽ|G;m««¼Õ‘h’IRLp°,µ‰<ÿ¥*‡ë>Ž´ÌÇRtA‰öjJäÂY<5&u„óNæÓÓ¿Md¡U§ÎkäÐÁJÛO{9’^¬C]Ó<ô;Ë:N“šK8KÏH1
I call the Graph endpoint to get the contents of the file like this:
public function getRawAttachmentContents($emailAddress, $messageId)
{
return $this->graph->createRequest("GET", "/users/$emailAddress/messages/$messageId/attachments/{attachmentId}")
->setReturnType(get_class(new \Microsoft\Graph\Model\FileAttachment()))
->execute();
}
This is what gets returned when I make the call. The contents look very different. It's like they're in a different format. How can I get them to be in the same format as the original? When I call the Graph API to get the raw contents (using the $value at the end) nothing gets returned.
Edit: So I figured out how to get the contents of the attachment as they appear when I open the file in Notepad++. I do this:
public function getRawAttachmentContents($emailAddress, $messageId, $attachmentId)
{
$attachment = $this->graph->createRequest("GET", "/users/$emailAddress/messages/$messageId/attachments/$attachmentId/\$value")
->execute();
$attachment->getRawBody()->rewind();
$file_contents = $attachment->getRawBody()->getContents();
return $file_contents;
}
However, when I try uploading the contents returned from that function, an attachment doesn't even get created in the draft message (before, when I uploaded the plain text, it was at least creating an attachment to the draft message, and I was getting a 201 created response on the final upload of the bytes, but the attachment was corrupt).
Related
Using Gravity Forms, I have a php form with a PDF file upload field. We pass the form data (json) to a third party API. However, it is sending the PDF as a url to the file, and we need to actually pass the contents of the PDF encoded in the body.
We can use the following filter to modify the request data before the webhook is set, but I don't know how to encode the actual file contents:
add_filter( 'gform_webhooks_request_data', 'modify_data', 10, 4 );
function modify_data( $request_data, $feed, $entry, $form ){
$request_data = // do something
return $request_data;
}
How is it possible to read the file contents of the PDF and base64 encode it?
Thank you!
I am trying to create a temporarily PDF file from raw PDF string.
This is my input, which is sent through an API (JSON):
{
"name": "pdffilename.pdf",
"content": "%PDF-1.2 [.......]%%EOF"
}
The "content" string is the actual PDF raw data string.
Now this is my controller, that handles the API request:
/**
* Function to convert a PDF file to text
*/
public function PDFtoText(Request $request)
{
$name = $request->name;
$content = $request->content;
//Save PDF file on the server (temp files).
$pdf = Storage::disk('local')->put('/temp_files/' . $name, $content);
return response()->json([
'result' => "Success"
], 200);
}
An actual file is created in the temp_files folder, with the name pdffilename.pdf. However I cannot open the file, as it says the file is "corrupt".
What am I doing wrong here?
the best way to save the content of the document or file is using the base64_encode function, this transform de content in base64 encode. Then when you need this content the unique process you need to do is to call the base64_decode function. I tried and works fine for me. Any questions only write me.
Goal: When client requests to see a file from server, i want the client's browser to ask what to do (open or download file). How can i build that?
So far i have methods like those:
public static function getFileContent($fullpath){
//yes, i can get both file and its extension
$file = File::get($fullpath);
$mimeType = File::extension($fullpath);
$response = Response::make($file, 200, array('content-type'=>$mimeType));
return $response;
}
and the other method calls the above
$path = $instance->the_file_path_on_the_database;
return MyClass::getFileContent($path);
In this case, if the uploaded file is PDF, png, jpeg etc. browser automatically opens the file, which is okay.
But when it comes to the *.xlsx or *.docx, browser asks me what to do but the file name isn't as the same as what i have stored on the database and it has no extension. Also the file is automatically renamed as the route's name.
Thanks in advance.
according to the docs
The download method may be used to generate a response that forces the
user's browser to download the file at the given path. The download
method accepts a file name as the second argument to the method, which
will determine the file name that is seen by the user downloading the
file. Finally, you may pass an array of HTTP headers as the third
argument to the method:
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
I've written a REST interface for my ownCloud app. I've method getFileFromRemote($path) which should return a JSON object with the file content.
Unfortunately this only works when the file that I've specified in $path is a plaintext file. When I try to call the method for an image or PDF the status code is 200 but the response is empty. For returning the file contents I use file_get_contents for retrieving the content.
Note: I know ownCloud has a WebDAV interface, but I want to solve this with REST only.
EDIT
This is the code server side (ownCloud):
public function synchroniseDown($path)
{
$this->_syncService->download(array($path));//get latest version
$content = file_get_contents($this->_homeFolder.urldecode($path));
return new DataResponse(['path'=>$path, 'fileContent'=>$content]);
}
The first line retrieves downloades the content on the ownCloud server and works completely.
You probably have to base64_encode your file content to make json_encode/decode handle it properly:
return new DataResponse([
'path'=>$path,
'fileContent' => base64_encode($content) // convert binary data to alphanum
]);
and then when receiving file via second side, you will have to always:
$fileContent = base64_decode($response['fileContent']);
It's only one, but ones of easiest way to handle that. Btw, sooner or later you will find that Mime-Type would be useful in response.
I've come across a bit of a problem and was wondering if anyone could point me in the right direction, I'm writing a email parser that parses emails and extracts particular info.
It parses plain text emails(the emails are in a set format) using regex, this works fine.
If an email has an attachment which is of type 3 && encoding = 3 && disposition = attachment then save the attachment to local disk.
My problem is step 2:
I foreach through each email structure if it has more than 2 parts I attempt to decode the attachment and save it to disk, but this is failing.
If I try to simply use file_put_contents I get a 0 KB File, I have given full permissions to the wamp server user, So I do not think it's file permissions and I have verified I can write by using mkdir.
file_put_contents(APPPATH . "attachments/". $partofpart->dparameters[0]->value, $partofpart); //$partofpart is part[2] of the full email structure
So I attempted to decode the part and save the decoded part instead using file_put_contents
$attachment = base64_decode($partofpart);
var_dump($attachment);
//then save the attachment with attachment name
file_put_contents(APPPATH . "attachments/". $partofpart->dparameters[0]->value, $attachment);
but this returns an error saying base64_decode requires an string not an object, how do I then convert my email-part-attachment to a string for use by base64_decode?
Even just writing that out I feel I'm missing something obvious and shouldn't require the extra steps.
Am I right in thinking the part IS the attachment? All the parameters lead me to believe so, Type, Subtype, size etc are all correct for the attachment.
Link to the entire scraper model
Thanks for reading and any help.
Below is a vardump of parts that meet the type/encoding/disposition checks
I have worked out the problem, I was not fetching the actual pdf back just its structure
So I wrote a function to retrieve the body of the particular email then used imap_base64 to encode then finally file_put_contents.
function getAttachment($msg_index, $part)
{
$mailbody = imap_fetchbody($this->conn,$msg_index,$part);
return $mailbody;
}
$attachment = imap_base64($this->email_model->getAttachment($email['index'], "2"));
//mkdir(APPPATH . "attachmentzs/");
//then save the attachment with attachment name
file_put_contents(APPPATH . "attachments/". $partofpart->dparameters[0]->value, $attachment);