Skip to content

Commit

Permalink
upload image file via Text API call for more flexibility in saved fil…
Browse files Browse the repository at this point in the history
…e location

Signed-off-by: Julien Veyssier <eneiluj@posteo.net>
  • Loading branch information
Julien Veyssier committed Nov 2, 2021
1 parent e6eca13 commit 15936b6
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 10 deletions.
3 changes: 2 additions & 1 deletion appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@

return [
'routes' => [
['name' => 'Image#downloadImageLink', 'url' => '/image/link', 'verb' => 'POST'],
['name' => 'Image#insertImageLink', 'url' => '/image/link', 'verb' => 'POST'],
['name' => 'Image#uploadImage', 'url' => '/image/upload', 'verb' => 'POST'],

['name' => 'Session#create', 'url' => '/session/create', 'verb' => 'PUT'],
['name' => 'Session#fetch', 'url' => '/session/fetch', 'verb' => 'POST'],
Expand Down
25 changes: 23 additions & 2 deletions lib/Controller/ImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

namespace OCA\Text\Controller;

use Exception;
use OCP\AppFramework\Http;
use OCA\Text\Service\ImageService;
use OCP\AppFramework\Controller;
Expand All @@ -49,17 +50,37 @@ public function __construct(string $appName,
parent::__construct($appName, $request);
$this->userId = $userId;
$this->imageService = $imageService;
$this->request = $request;
}

/**
* @NoAdminRequired
*/
public function downloadImageLink(string $link): DataResponse {
$downloadResult = $this->imageService->downloadImageLink($link, $this->userId);
public function insertImageLink(string $link): DataResponse {
$downloadResult = $this->imageService->insertImageLink($link, $this->userId);
if (isset($downloadResult['error'])) {
return new DataResponse($downloadResult, Http::STATUS_BAD_REQUEST);
} else {
return new DataResponse($downloadResult);
}
}

/**
* @NoAdminRequired
*/
public function uploadImage(string $textFilePath): DataResponse {
try {
$file = $this->request->getUploadedFile('image');
if ($file !== null && isset($file['tmp_name'], $file['name'])) {
$newFileContent = file_get_contents($file['tmp_name']);
$newFileName = $file['name'];
$uploadResult = $this->imageService->uploadImage($textFilePath, $newFileName, $newFileContent, $this->userId);
return new DataResponse($uploadResult);
} else {
return new DataResponse(['error' => 'No uploaded file'], Http::STATUS_BAD_REQUEST);
}
} catch (Exception $e) {
return new DataResponse(['error' => 'Upload error'], Http::STATUS_BAD_REQUEST);
}
}
}
26 changes: 25 additions & 1 deletion lib/Service/ImageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,35 @@ public function __construct(IRootFolder $rootFolder,
$this->logger = $logger;
}

/**
* @param string $textFilePath
* @param string $newFileName
* @param string $newFileContent
* @param string $userId
* @return array
*/
public function uploadImage(string $textFilePath, string $newFileName, string $newFileContent, string $userId): array {
$fileName = (string) time() . '-' . $newFileName;
$saveDir = $this->getOrCreateTextDirectory($userId);
if ($saveDir !== null) {
$savedFile = $saveDir->newFile($fileName, $newFileContent);
$path = preg_replace('/^files/', '', $savedFile->getInternalPath());
return [
'name' => $fileName,
'path' => $path,
];
} else {
return [
'error' => 'Impossible to create /Text directory',
];
}
}

/**
* @param string $link
* @return array
*/
public function downloadImageLink(string $link, string $userId): array {
public function insertImageLink(string $link, string $userId): array {
$fileName = (string) time();
$saveDir = $this->getOrCreateTextDirectory($userId);
if ($saveDir !== null) {
Expand Down
39 changes: 33 additions & 6 deletions src/components/MenuBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -351,20 +351,36 @@ export default {
})
},
uploadImage(targetFilePath, image) {
const client = OC.Files.getClient()
client.putFileContents(targetFilePath, image, {
contentType: image.type,
contentLength: image.size,
overwrite: false,
const formData = new FormData()
formData.append('image', image)
formData.append('textFilePath', this.filePath)
// TODO change the url if we are in a public context
const url = generateUrl('/apps/text/image/upload')
axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
this.insertImage(targetFilePath, this.imageCommand)
console.debug('upload RESPONSE', response.data)
this.insertImage(response.data?.path, this.imageCommand)
}).catch((error) => {
console.error(error)
showError(error?.response?.data?.error)
}).then(() => {
this.imageCommand = null
this.uploadingImage = false
})
// this can be done in a simple fashion with the file client
/*
const client = OC.Files.getClient()
client.putFileContents(targetFilePath, image, {
contentType: image.type,
contentLength: image.size,
overwrite: false,
}).then((response) => {
this.insertImage(targetFilePath, this.imageCommand)
})
*/
},
onImageLinkUpdateValue(newImageLink) {
// this avoids the input being reset on each file polling
Expand Down Expand Up @@ -412,6 +428,17 @@ export default {
const encodedPath = path.split('/').map(encodeURIComponent).join('/')
const meta = Object.entries(appendMeta).map(([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&')
const src = `${encodedPath}?fileId=${fileInfo.id}#${meta}`
/*
const getParams = {
fileId: fileInfo.id,
}
const getParamsArray = []
for (const k in getParams) {
getParamsArray.push(encodeURIComponent(k) + '=' + encodeURIComponent(getParams[k]))
}
const src2 = window.location.protocol + '//' + window.location.host + generateUrl('/apps/text/image?') + getParamsArray.join('&')
console.debug('SRC', src2)
*/
command({
src,
Expand Down

0 comments on commit 15936b6

Please sign in to comment.