Skip to content

Instantly share code, notes, and snippets.

@ryantan
Last active May 8, 2018 06:13
Show Gist options
  • Save ryantan/d1816f95ae3a60c6e2b1ea13142b00f5 to your computer and use it in GitHub Desktop.
Save ryantan/d1816f95ae3a60c6e2b1ea13142b00f5 to your computer and use it in GitHub Desktop.
A drupal 8 controller function to handle photo upload requests.
public function uploadPhoto(Profile $profile, Request $request) {
if ($request->getMethod() === 'POST' || $request->getMethod() === 'PUT') {
// Decode body
$body_raw = $request->getContent();
$body = json_decode($body_raw);
$imageName = $body->name;
$imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $body->data));
\Drupal::logger('uploadPhoto')->notice('$imageName: %imageName, $imageData: %imageData', ['%imageName' => $imageName, '%imageData' => $imageData]);
$directory = $this->ensureProfileImageDirectory();
$destination = $directory . $imageName;
$saved_file = file_save_data($imageData, $destination);
\Drupal::logger('uploadPhoto')->notice('$directory: %directory, $destination: %destination, $saved_path: %saved_path', [
'%directory' => $directory,
'%destination' => $destination,
'%saved_path' => $saved_file->getFileUri(),
]);
$file_usage = \Drupal::service('file.usage');
$file_usage->add($saved_file, 'onboarding', 'profile', $profile->id());
$profile->field_profile_image = $saved_file;
$profile->save();
// Doesn't work with multi-part requests from react, not sure why.
// $validators = [
// 'file_validate_extensions' => ['jpg jpeg gif png'],
// ];
// if (!$file = file_save_upload('photo', $validators, FALSE, $delta = 0)){
// \Drupal::logger('file')->notice('The photo upload failed for profile id %profile_id', ['%profile_id' => $profile->id()]);
//
// return JsonResponse::create(['errorMessage' => 'The photo could not be saved.'], 500);
// }
// \Drupal::logger('file')->notice('The photo uploaded as %file_id', ['%file_id' => $file->id()]);
$body = [
'success' => 1,
'file_id' => $saved_file->id(),
'file_uri' => $saved_file->getFileUri(),
'file_url' => $saved_file->url(),
];
return JsonResponse::create($body);
}
if ($request->getMethod() === 'GET') {
return JsonResponse::create(['errorMessage' => 'Use post request to upload photo to profile %profile.', ['%profile' => $profile->id()]], 400);
}
return JsonResponse::create(['errorMessage' => 'This call only accepts post requests.'], 400);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment