Конечно, все нормально. Я использую этот класс в PHP:
<?php
function thumbnail( $img, $source, $dest, $maxw, $maxh ) {
$jpg = $source.$img;
if( $jpg ) {
list( $width, $height ) = getimagesize( $jpg ); //$type will return the type of the image
$source = imagecreatefromjpeg( $jpg );
if( $maxw >= $width && $maxh >= $height ) {
$ratio = 1;
}elseif( $width > $height ) {
$ratio = $maxw / $width;
}else {
$ratio = $maxh / $height;
}
$thumb_width = round( $width * $ratio ); //get the smaller value from cal # floor()
$thumb_height = round( $height * $ratio );
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
imagecopyresampled( $thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height );
$path = $dest.$img."_thumb.jpg";
imagejpeg( $thumb, $path, 75 );
}
imagedestroy( $thumb );
imagedestroy( $source );
}
?>
imagejpeg( $thumb, $path, 75 );
где вы хотите размер и качество изображения после загрузки.
Вызов в скрипте PHP:
if( isset( $_FILES['img-content'] ) ) {
$img = str_replace( " ","_",$_FILES['img-content']['name'] );
move_uploaded_file( $_FILES['img-content']['tmp_name'], "../../images/content/".$img );
$source = "../../images/content/";
$dest = "../../images/thumb/";
thumbnail( $img, $source, $dest, 480, 400 );
По умолчанию axios сериализует объекты JavaScript в JSON. Чтобы вместо этого отправлять данные в формате application / x-www-form-urlencoded, вы можете использовать один из следующих вариантов.
blockquote>Вы устанавливаете заголовок
Content-Type
, в котором утверждается, что вы отправляете данныеapplication/x-www-form-urlencoded
, но вы не сделали ничего из того, что предлагается в документации для создания данных в этом формате.
В стороне:
'Access-Control-Request-Headers': 'authorization',
Это заголовок ответа , нет смысла включать его в запрос.
Было две проблемы - одна, как указал Квентин ниже, мне нужно было структурировать данные JSON, если я собираюсь использовать application/x-www-form-urlencoded
(что требуется для API Yahoo). [115 ]
Второй проблемой была моя обработка обещаний. refreshAuthorizationToken
не должен быть ни асинхронным, ни использовать await, он должен просто возвращать axios - это вызывающая функция , которая должна использовать async / await.
Рабочий код:
const qs = require('qs');
const fs = require('fs');
const axios = require('axios');
const consumerKey = `myConsumerKeyHere`;
const consumerSecret = `myConsumerSecretHere`;
const authHeader = Buffer.from(`${consumerKey}:${consumerSecret}`, `binary`).toString(`base64`);
const authEndpoint = `https://api.login.yahoo.com/oauth2/get_token`;
function writeToFile(data, file, flag) {
if (flag === null) flag = `a`;
fs.writeFile(file, data, {flag: flag}, (err) => {
if (err) {
console.error(`Error in writing to ${file}: ${err}`);
}
});
}
function refreshAuthorizationToken(token) {
return axios({
url: authEndpoint,
method: 'post',
headers: {
'Authorization': `Basic ${authHeader}`,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
},
data: qs.stringify({
redirect_uri: 'oob',
grant_type: 'refresh_token',
refresh_token: token
}),
timeout: 1000,
}).catch((error) => {
console.log(`Some kind of horrible error in refreshAuthorizationToken: ${error}`);
});
}
async function reload() {
const returnVal = await refreshAuthorizationToken(credentials.refresh_token);
if (returnVal) {
if (returnVal.data && returnVal.data.access_token) {
writeToFile(JSON.stringify(returnVal.data), authFile, 'w');
}
}
}
reload();