Upload image to imgur via API - Javascript - javascript

I'm trying to upload an image to imgur via their API and i'm receiving an error 400.
{"data":{"error":"Invalid URL (Array)","request":"\/3\/image","method":"POST"},"success":false,"status":400}
My code:
const submitForm = async (event, imageFile) => {
axios.post(
"https://api.imgur.com/3/image",
{ image: imageFile, type: "file" },
{
headers: {
Authorization: `Client-ID ${process.env.REACT_APP_IMGUR_CLIENT_ID}`,
},
}
);
};
When printing "imageFile":
File {
name: "1545572599598.jpg",
lastModified: 1545573667488,
lastModifiedDate: Sun Dec 23 2018 16:01:07 GMT+0200,
webkitRelativePath: "",
size: 291376, …
}
searched like everywhere on the internet.
somone have seen that before?
Thanks

Related

run a function when insert file on sweetAlert

I'm changing an input file for a button that opens a new window using sweetAlert2
$('#btn-file').on('click', function (){
(async () =>{
let { value: file } = await Swal.fire({
title: 'Select image',
html: 'You can download a model for your work here',
input: 'file',
showCancelButton: true,
inputAttributes: {
'accept': '.csv',
'aria-label': 'Upload your CSV file'
}
})
if (file) {
const reader = new FileReader()
reader.onload = (e) => {
//CALL TO A FUNCTION
}
reader.readAsDataURL(file);
}
})();
});
I want to call my old function that it works correctly but is an input file
$("#csv-file").change(handleFileSelect);
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
//rest of my code....
I want to call to handleFileSelect, actually, that function runs when the input file has changes, I want to run with my sweetAlert
how can I do?
if I just only call to handleFileSelect(); I get this error
create:335 Uncaught TypeError: Cannot read property 'target' of undefined
Update to louys answer:
my Papa.parse(file) is not working, in the console.log for file I get this
console.log(file); when all is working
File {name: "task import.csv", lastModified: 1613002044713, lastModifiedDate: Wed Feb 10 2021 20:07:24 GMT-0400 (hora de Bolivia), webkitRelativePath: "", size: 96, …}
lastModified: 1613002044713
lastModifiedDate: Wed Feb 10 2021 20:07:24 GMT-0400 (hora de Bolivia) {}
name: "task import.csv"
size: 96
type: ""
webkitRelativePath: ""
__proto__: File
console.log(file); when I use the solution
data:application/octet-stream;base64,R29vZ2xlIFBsYWNlIFVSTCxCdXNpbmVzcyBUeXBlDQpodHRwOi8vd3d3LnJlc3RhdXJhbnQuY29tLFJlc3RhdXJhbnQNCmh0dHA6Ly93d3cuaG90ZWwuY29tLEhvdGVs
If I download that file link and put a .csv extension, the file is correct, but incompatible with Papa.parse
You don't need to use a FileReader here. If there is a file... Pass it to your function.
$('#btn-file').on('click', function (){
(async () =>{
let { value: file } = await Swal.fire({
title: 'Select image',
html: 'You can download a model for your work here',
input: 'file',
showCancelButton: true,
inputAttributes: {
'accept': '.csv',
'aria-label': 'Upload your CSV file'
}
})
if (file) {
//CALL TO A FUNCTION
handleFileSelect(file); // Try passing the file result directly
})();
});
function handleFileSelect(file) {
// Remove this... The file was passed as argument
//var file = evt.target.files[0];
//rest of my code....

Why is my fetch command not passing the body to AWS API Gateway?

I have a stage in AWS API Gateway that takes POST requests. If I call this API Gateway with Postman, everything works as expected. I can see in CloudWatch logs, that the body of the POST is present. The body is as follows (shortened):
{
"Success": "1",
"Item": {
"IngameName": "SomeName",
"Timestamp": "Mon Oct 12 2020 19:07:29 GMT+0100 (British Summer Time)"
}
}
I also set a header for the content type in Postman: Content-Type : application/json.
I try to make the same call again using fetch in JavaScript:
let testJson = {
"Success": "1",
"Item": {
"IngameName": "SomeName",
"Timestamp": "Mon Oct 12 2020 19:07:29 GMT+0100 (British Summer Time)"
}
};
fetch(apiGatewayAddressLocal, {
method: 'POST',
body: JSON.stringify(testJson),
headers: {
'Content-Type': 'application/json'
}
});
The fetch call reaches API Gateway successfully, but CloudWatch logs say that the body is empty. I have also tried doing json.parse instead of json.stringify but this gives me Unexpected token errors in the console. I saw some solutions including Accept:application/json as a header, which I tried but does not fix the solution. I also tried the solution suggested here, but then I could not reach API Gateway at all.
I have double checked that apiGatewayAddressLocal definitely contains a valid link, it is the same as I used in Postman
Why is my fetch call not passing any body to API Gateway?
This problem was happening because the fetch command was not included inside an async function, and the fetch command needed to be used with await. I also added in a no-cors mode with the fetch operation.
async function someFunction(callback) {
let testJson = {
"Success": "1",
"Item": {
"IngameName": "SomeName",
"Timestamp": "Mon Oct 12 2020 19:07:29 GMT+0100 (British Summer Time)"
}
};
await fetch(apiGatewayAddressLocal, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(testJson)
});
callback();
}

HTML POST request method returns status 200 and file doesn't update

I am working on a system to upload a picture to the server.
When the file doesn't exist on the server the client receives status code 404.
When the server does have a file called in the same name as the file that the client requests to update, It receives status code 200 but the file doesn't update on the server, just no change at all.
Code:
HTML input:
<form enctype="multipart/form-data" method="post" id="pfp-upload">
<p>Please upload your new profile picture:</p>
<input type="file" class="form-control-file" id="new-pfp" accept="image/x-png,image/jpeg">
</form>
<button type="button" class="btn btn-primary" title="Popover title" data-content="" onclick="updatePfp(document.getElementById('pfp-upload') ,document.getElementById('new-pfp'))">Save changes</button>
JavaScript code running when the submit button is clicked:
async function updatePfp(form, pfp) {
var formData = new FormData(form);
let photo = pfp.files[0];
console.log(photo);
var oReq = new XMLHttpRequest();
oReq.open("POST", "/media/" + photo.name, true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("File uploaded!");
} else {
console.log("There was an error (" + oReq.status + ") while sending the file!");
}
};
oReq.send(formData);
}
Console output when the file doesn't exist on the server:
File {name: "mainmenu.png", lastModified: 1567069340052, lastModifiedDate: Thu Aug 29 2019 12:02:20 GMT+0300 (Israel Daylight Time), webkitRelativePath: "", size: 1617, …}
POST http://domainCensored/media/mainmenu.png 404 (Not Found)
There was an error (404) while sending the file!
Console output when the file exists on the server:
File {name: "mainmenu.png", lastModified: 1567069340052, lastModifiedDate: Thu Aug 29 2019 12:02:20 GMT+0300 (Israel Daylight Time), webkitRelativePath: "", size: 1617, …}
File uploaded!
After that output nothing changed on the server.
EDIT:
After some steps, I got the following:
JavaScript code:
async function updatePfp(form, pfp) {
var formData = new FormData();
let photo = pfp.files[0];
formData.append('myFile', photo);
console.log(photo);
fetch('/media/' + photo.name, {
method: 'POST',
body: formData,
}).then(response => {
return response.text();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
}
Console output (when the file with the same name is on the server):
File {name: "mainmenu.png", lastModified: 1567069340052, lastModifiedDate: Thu Aug 29 2019 12:02:20 GMT+0300 (Israel Daylight Time), webkitRelativePath: "", size: 1617, …}
After that line, there is another blank line, chrome says it's from this line:
console.log(data);
This still doesn't work.

Accessing a Bucket virtual-hosted-style url deprecated? (aws s3)

Not sure if this is the best place to post this question, please redirect me if this isn't then I will remove the post and post it to the correct location.
I know that recently amazon s3 has changed their url while accessing files.
It used to be something like http://s3.amazonaws.com/<bucket> or http://s3.<region>.amazonaws.com/<bucket>
But there's been changes into http://<bucket>.s3-<aws-region>.amazonaws.com or http://<bucket>.s3.amazonaws.com, due to this documentation https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro
http://<bucket>.s3.amazonaws.com would not be reachable after March 20, 2019, BUT when I use aws-sdk in javascript to do file upload with skipper-better-s3 the url I get in return from aws is http://<bucket>.s3.amazonaws.com/<Key>
If that url is not suppose to be reachable why would aws return such url? (I can still access the file using the url)
If that url is not suppose to be reachable in the near future, am I suppose to add in the region myself or modify the url myself instead of using the url returned by aws?
Or it might my code's problem?
Below is my code for the upload
const awsOptions = { // these fields are different because this uses skipper
adapter: require('skipper-better-s3'),
key: aws_access_key,
secret: aws_secret_key,
saveAs: PATH,
bucket: BUCKET,
s3params: {
ACL: 'public-read'
},
}
const fieldName = req._fileparser.upstreams[0].fieldName;
req.file(fieldName).upload(awsOptions, (err, filesUploaded) => {
if (err) reject(err);
const filesUploadedF = filesUploaded[0]; // F = first file
const url = filesUploadedF.extra.Location; // image url -> https://<bucket>.s3.amazonaws.com/<Key>
console.log(url, 'urlurlurl');
});
filesUploadedF would return
UploadedFileMetadata {
fd: '<Key>',
size: 4337,
type: 'image/png',
filename: 'filename.png',
status: 'bufferingOrWriting',
field: 'image',
extra:
{ ETag: '111111111111111111111',
Location: 'https://<bucket>.s3.amazonaws.com/<Key>',
key: '<key>',
Key: '<Key>',
Bucket: '<Bucket>',
md5: '32890jf32890jf0892j3f',
fd: '<Key>',
ContentType: 'image/png' }
}
The documentation you linked to for http://<bucket>.s3.amazonaws.com style naming says this:
Note
Buckets created in Regions launched after March 20, 2019 are not reachable via the https://bucket.s3.amazonaws.com naming scheme.
The wording there is important. They're only talking about new regions brought online after March 20, 2019.
To date, that's only buckets created in Middle East (Bahrain) and Asia Pacific (Hong Kong) regions.

Bizzare behaviour from Amazon SQS Javascript SDK (sendMessage)

I'm at the end of my rope here, so I'll keep it short and simple. Here's my code sample:
var message = JSON.stringify(value)
var url = process.env.SQS_URL + 'ts-notifications'
services.queue.sendMessage({
MessageAttributes: {
"responseId": {
DataType: 'String',
StringValue: responseIdentifier.toString('hex', true)
},
"surveyId": {
DataType: 'String',
StringValue: surveyIdentifier.toString('hex', true)
},
"itemId": {
DataType: 'String',
StringValue: key
}
},
MessageBody: message,
QueueUrl: url,
DelaySeconds: 0
}, function(err, data) {
if (err) {
cb(err)
} else {
cb()
}
})
Running this gets me this error:
{ [UnexpectedParameter: Unexpected key 'MessageAttributes' found in params]
message: 'Unexpected key \'MessageAttributes\' found in params',
code: 'UnexpectedParameter',
time: Sat Jan 07 2017 20:06:33 GMT+0000 (UTC) }
Here's a link to the AWS SQS Javascript SDK for sendMessage: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessage-property
It seems pretty clear to me that MessageAttributes is a valid parameter of sendMessage. I'm open to any and all suggestions, because this one is stumping me!
P.S., yes, I'm on the correct API version (there's only one anyway), and the variables above correspond to valid things higher up in the code.
Thanks all!

Categories