The following Imgur Upload API isn't working: *https://api.imgur.com/3/upload
*. Any idea what else I can use or if they got a new one? I looked at the docs, but couldn't find anything although I might be missing something here: https://apidocs.imgur.com/?version=latest
Here's the code I use to upload images to imgur. The endpoint is different, I don't know if yours work.
const uploadImg = function(file: any) {
// Begin file upload
console.log("Uploading file to Imgur..");
var apiUrl = 'https://api.imgur.com/3/image';
var apiToken = <your-token>;
var settings: any = {
async: false,
crossDomain: true,
processData: false,
contentType: false,
type: 'POST',
url: apiUrl,
mimeType: 'multipart/form-data'
};
var formData = new FormData();
formData.append("image", file);
formData.append("album", "your-album-name"); // optional
settings.data = formData;
return axios(apiUrl, {
method: 'post',
data: formData,
headers: {Authorization: 'Bearer ' + apiToken,
Accept: 'application/json'}});
}
Related
I create my API using v3 of Drive Api and usign uploadType=resumable, the server return me status code 200 and the metadata for the file, but when I see in drive, the file isn't there
// Client
googleClientRequest() {
const keysEnvVar = process.env["CREDS"];
if (!keysEnvVar) {
throw new Error("The $CREDS environment variable was not found!");
}
const keys = JSON.parse(keysEnvVar);
return new GoogleAuth({
scopes: [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
],
credentials: keys,
});
// Initial request
const initialFile = await client.request({
url:
"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
Accept: "application/json",
},
data: {
name: `${job.data.callId}.mp3`,
},
});
// File upload
async doUpload(fileLink: string, driveLink: string) {
const client = this.googleClientRequest();
const { data, headers } = await axios({ // The file comes from zoom api is a recorder
method: "GET",
url: fileLink,
responseType: "arraybuffer",
});
const response = await client.request({
url: driveLink,
headers: {
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": "audio/mp3",
"X-Upload-Content-Length": headers["zoom-file-size"],
},
method: "POST",
data: Buffer.from(data),
});
console.log(response.status, response.data, response.statusText);
return response;
}
// The response
200 OK
{
kind: 'drive#file',
id: '######',
name: '1e9af0f9-9d3e-4287-a9fa-7cb3d229c1ad.mp3',
mimeType: 'audio/mp3'
}
I try everything, I try with this example Angular 2+ HTTP POST and GDrive API. Resumable file upload with name
I want to use Shopify api. And I want to upload video with this API. So official document like that:
https://shopify.dev/api/examples/product-media#videos-3d-models-post-request
So, I created an axios config and I tried to send request.
My code snipped like that:
let fd = new FormData();
fd.append("bucket", bucket);
fd.append("key", key);
fd.append("policy", policy);
fd.append("cache-control", cacheControl);
fd.append("x-amz-signature", xAmzSignature);
fd.append("x-amz-algorithm", xAmzAlgorithm);
fd.append("x-amz-date", xAmzDate);
fd.append("file", fs.createReadStream('./milk.mp4'));
const config: AxiosRequestConfig = {
url: "https://shopify-video-production-core-originals.s3.amazonaws.com/",
data: fd,
method: "POST",
headers: { "Content-Type": "multipart/form-data" }
}
try {
const videoPost = await axios(config);
}
catch (err) {
console.log(err)
}
So, I getting an error like that:
....
....
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<Error><Code>MalformedPOSTRequest</Code><Message>The body of your POST request is not well-formed multipart/form-data.</Message><RequestId>184VT99AXG4J6FWW</RequestId><HostId>1IBK7dCgApORGZnaGxS/n22Ftgw0fRBW1EnMuhFpEPek5R3iwsa2T9MH2q8A31l1AU9lhAb2WYA=</HostId></Error>'
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
Why Im getting this error? How can I solve this? Please Help
As the documentation says, there are two versions for the formdata syntax.
Change the code as mentioned below:
fd.append("file", fs.createReadStream('./milk.mp4'));
...
const config: AxiosRequestConfig = {
url: "https://shopify-video-production-core-originals.s3.amazonaws.com/",
data: fd,
method: "POST",
headers: { "Content-Type": "multipart/form-data" }
}
to
fd.append("file", fs.createReadStream('./milk.mp4'), {filename: 'milk.mp4'});
...
const config: AxiosRequestConfig = {
url: "https://shopify-video-production-core-originals.s3.amazonaws.com/",
data: fd,
method: "POST",
headers: fd.getHeaders()
}
Here is the Solution
const config: AxiosRequestConfig = {
url: "https://shopify-video-production-core-originals.s3.amazonaws.com/",
data: fd,
method: "POST",
headers: { ...fd.getHeaders() } // <-- This is the Fix.
}
Post file as raw body in AXIOS NodeJS. I tried many ways to achieve this but none of them worked.
What i have tried ?
var file = fs.readFileSync("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg").toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg",{encoding:"utf8"}).toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg");
file = Buffer.from(file).toString('utf8')
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.createReadStream("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
But none of them worked as i wanted.
Actual working example from JQuery AJAX in Browser
var fileupload = $("#inpFile")[0];
var file = fileupload.files[0];
$.ajax({
url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
type: 'POST',
success: function (response) {
DisplayMessage(response);
},
data: file,
contentType: false,
processData: false
});
Have you tried setting the content-type header?
Per Talg123 I found that if you set contentType to false in jQuery it might be equivalent to multipart/form-data.
client side:
async function main(){
try{
const buffer = new ArrayBuffer(8);
const data = new FormData();
const blob = new Blob([buffer],{type : 'multipart/form-data'});
data.append('data', blob);
const options = {
url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
method: 'POST',
headers: { 'content-type': 'multipart/form-data' },
data
};
let result = await axios(options);
console.log(result);
}catch(e){
console.error("error",e);
}
}
main()
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
server side per https://github.com/axios/axios/issues/1006#issuecomment-584840380
const axios = require('axios');
const FormData = require('form-data');
// Where buffer is a file
formData.append('file', buffer);
// Added a promise version like seen in earlier comments to get this
const contentLength = await formData.getLength();
await axios(`<ENDPOINT>`, {
method: 'POST',
baseURL: <BASE_URL>,
params: {
fileName: '<FILE_NAME>.png'
},
headers: {
authorization: `Bearer <TOKEN>`,
...formData.getHeaders(),
'content-length': contentLength
},
data: formData
});
js fiddle for image/jpeg
https://jsfiddle.net/bn7yLh61/
I received multiple pdf files and must download it from a REST-API.
After auth and connect I try to download the file with request-promise:
const optionsStart = {
uri: url,
method: 'GET',
headers: {
'X-TOKEN': authToken,
'Content-type': 'applcation/pdf'
}
}
request(optionsStart)
.then(function(body, data) {
let writeStream = fs.createWriteStream(uuid+'_obj.pdf');
console.log(body)
writeStream.write(body, 'binary');
writeStream.on('finish', () => {
console.log('wrote all data to file');
});
writeStream.end();
})
The request create a pdf (approximately 1-2MB) but I can't open it. (Mac Preview show blank pages and adobe show = >
There was an error opening this document. There was a problem reading
this document (14).
I have no information about the API Endpoint where I download the files. Just have this curl:
curl -o doc.pdf --header "X-TOKEN: XXXXXX"
http://XXX.XXX/XXX/docs/doc1
Where is my mistake?
Update:
I opened the file in edit and the file looks like that:
Don't have any experience with that :-)
Add encoding: 'binary' to your request options:
const optionsStart = {
uri: url,
method: "GET",
encoding: "binary", // it also works with encoding: null
headers: {
"Content-type": "application/pdf"
}
};
Add encoding: null to your request options:
const optionsStart = {
uri: url,
method: "GET",
encoding: null,
headers: {
"Content-type": "application/pdf"
}
};
Then, turn the response into a Buffer (if necessary):
const buffer = Buffer.from(response);
try this
const optionsStart = {
uri: url,
method: 'GET',
headers: {
'X-TOKEN': authToken,
'Content-type': 'application/pdf'
},
encoding: null
}
request(optionsStart, (err, resp) => {
let writeStream = fs.createWriteStream(uuid + '_obj.pdf');
writeStream.write(resp.body, 'binary');
writeStream.on('finish', () => {
console.log('wrote all data to file');
});
writeStream.end();
})
I am receiving http POST response OK 200, but I see no file present on JIRA issue. From my research I can understand that it could be some problem with formData I am sending with request. Below is my code:
var newBuffer = new Buffer(req.Payload, 'base64');
var myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
frequency: 10, // in milliseconds.
chunkSize: 2048 // in bytes.
});
// With a buffer
myReadableStreamBuffer.put(newBuffer);
var formData = {
'file': {
'content': myReadableStreamBuffer,
'filename': req.FileName,
'mimeType': req.MimeType //mimeType from JSON
}
};
var options = {
url: 'https://comapny.atlassian.net/rest/api/2/issue/' + req.ReferenceId + '/attachments',
method: "POST",
json: true,
headers: {
'ContentType': 'multipart/form-data',
'Authorization': 'Basic ' + new Buffer(config.jira.jiraUser.userName + ':' + config.jira.jiraUser.password).toString('base64'),
'X-Atlassian-Token': 'nocheck'
},
formData: JSON.stringify(formData)
};
request(options,
function (error, response, body) {
if (error) {
errorlog.error(`Error Message : PostAttachmentToCSMS : ${error}`);
return response.statusCode;
}
else {
successlog.info(`Attachment posted for issue Key: ${req.ReferenceId} ${response.statusMessage}`);
return response.statusCode;
}
});
I can write file from myReadableStreamBuffer, so that seems ok. Please help me to identify the problem. Many thanks!
After spending some more time on it, I have found the correct format for formData:
var newBuffer = new Buffer(req.Payload, 'base64');
var formData = {
file: {
value: newBuffer,
options: {
filename: req.FileName,
contentType: req.MimeType
}
}
};
For whom like me getting errors with this API.
After struggling so many hrs on this thing, I finally found this works like a charm. I've got "XSRF check failed" 403/404 error message before writing this code.
// Don't change the structure of formData.
const formData = {
file: {
value: fs.createReadStream(filepath),
options: {
filename: filename,
contentType: "multipart/form-data"
}
}
};
const header = {
"Authentication": "Basic xxx",
// ** IMPORTANT **
// "Use of the 'nocheck' value for X-Atlassian-Token
// has been deprecated since rest 3.0.0.
// Please use a value of 'no-check' instead."
"X-Atlassian-Token": "no-check",
"Content-Type": "multipart/form-data"
}
const options = {
url: "http://[your_jira_server]/rest/api/2/issue/[issueId]/attachments",
headers: header,
method: "POST",
formData: formData
};
const req = request(options, function(err, httpResponse, body) {
whatever_you_want;
};
I was able to post attachments to JIRA using axios in the following way:
const axios = require('axios');
const FormData = require('form-data')
const fs = require('fs');
const url = 'http://[your_jira_server]/rest/api/2/issue/[issueId]/attachments';
let data = new FormData();
data.append('file', fs.createReadStream('put image path here'));
var config = {
method: 'post',
url: url,
headers: {
'X-Atlassian-Token': 'no-check',
'Authorization': 'Basic',
...data.getHeaders()
},
data: data,
auth: {
username: '',
password: ''
}
};
axios(config)
.then(function (response) {
res.send({
JSON.stringify(response.data, 0, 2)
});
})
.catch(function (error) {
console.log(error);
});