Upload and send string as file via telegram bot - javascript

I have a string that I want to send via a telegram bot, but not as a message (it's rather long) but as a file.
However I have some problems in creating and uploading this file to Telegram (since I need to post the file using multipart/form-data as specified in the API docs https://core.telegram.org/bots/api#sending-files).
Inspired by https://stackoverflow.com/a/22858914/4869973 I tried the following:
var file = new Blob([enc_data], {type: 'text/plain'});
var formData = new FormData();
formData.append('chat_id', '<id>');
formData.append('document', file);
var request = new XMLHttpRequest();
request.open('POST', 'https://api.telegram.org/bot<token>/sendDocument');
request.send(FormData);
but I only get a generic error POST https://api.telegram.org/bot<token>/sendDocument 400 (Bad Request)
I have never used XMLHttpRequest so I'm probably messing up with its usage but I can't find any solution.
Alternatives (possibly using plain js) are welcome.

Your variable naming was wrong. You named the formdata as formData and then when you sent the request you called it FormData.
Copy and paste this code, it should work. I tested it and it does. Make sure to replace the chat_id and token with valid ones else it won't work.
var chat_id = 3934859345; // replace with yours
var enc_data = "This is my default text";
var token = "45390534dfsdlkjfshldfjsh28453945sdnfnsldfj427956345"; // from botfather
var blob = new Blob([enc_data], { type: 'plain/text' });
var formData = new FormData();
formData.append('chat_id', chat_id);
formData.append('document', blob, 'document.txt');
var request = new XMLHttpRequest();
request.open('POST', `https://api.telegram.org/bot${token}/sendDocument`);
request.send(formData);

Related

Add attachemet to a ticket using xhr2 for jira rest api

I am trying to upload a file to a ticket using Jira rest api and xhr2 using node.js with electron
Here is my code
var XMLHttpRequest = require('xhr2')
var xhr = new XMLHttpRequest();
const fs = require('fs');
const filePath = 'test2.txt';
const form = new FormData();
const stats = fs.statSync(filePath);
const fileSizeInBytes = stats.size;
const fileStream = fs.createReadStream(filePath);
form.append('file', fileStream, {knownLength: fileSizeInBytes});
xhr.open("POST", "https:/myInstance/rest/api/2/issue/ticketid/attachments", true);
xhr.setRequestHeader("Authorization" , "Basic "+ Buffer.from("user" + ":" + "token").toString("base64"));
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-Atlassian-Token','no-check');
xhr.send(form);
I am getting the following error:
unsupported send() data [object FormData]
I am able to attach a file using:
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-attachments/#api-rest-api-3-issue-issueidorkey-attachments-post
example
but I want to know what is the problem with my previous code
I tried to add these to the header:
xhr.setRequestHeader('processData', false);
xhr.setRequestHeader('contentType',false);
it didn't help, also I tried to add:
xhr.setRequestHeader("Content-type", "multipart/form-data");
also it didn't work
The problem is in xhr itself
in the documentation it was mentioned that:
The following standard features are not implemented.
FormData
Blob
file:// URIs
data: URIs
upload progress events
synchronous operation
Same-origin policy checks and CORS
cookie processing

How do I upload the file at a URL using XHRWebRequest?

In a chrome extension I have a url stored as ctx.srcUrl. I am trying to upload the file that the URL points to onto a server. I can upload a file object using XHR with:
function uploadFile(file) {
var xhr = new XMLHttpRequest()
var formData = new FormData()
formData.append('upload', file)
xhr.open('POST', 'https://endpoint.com/upload')
xhr.withCredentials = true
xhr.send(formData)
}
Where file is a Javascript File object (https://developer.mozilla.org/en-US/docs/Web/API/File). I can also download an object using:
function downloadFile() {
const request = new XMLHttpRequest()
request.open('GET', ctx.srcUrl, true)
request.responseType = 'blob'
request.onload = function() {
// response is stored in `request.response`
}
request.send()
}
I'm struggling to work out how to link them up in an efficient manner however, preferably without keeping all of the response in memory at once (using streaming)? The best way I can find of doing it is using FileReader.readAsDataURL() but that has a file limit of ~256MB and some files might be larger than that.
There must be a better way of doing this, can anyone point me in the right direction?

Javascript send video blob to PHP - how to also send mimetype?

I'm generating a blob in JavaScript via a recorded video stream (MediaRecorder).
The resultant file ends up as a .webm, as confirmed by ffmpeg. So far, so good. Here's what I'm doing.
//promises container
let dfds = [];
//promise 1 - get blob file content
dfds.push(new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open('GET', file_url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) resolve(this.response);
};
xhr.send();
}));
//(other non-pertinent promises omitted here)
//when ready, build and send request
Promise.all(dfds).then(resolution_data => {
let req = new XMLHttpRequest(), fd = new FormData();
fd.append('title', title);
fd.append('file', resolution_data[0]); //<-- the blob
req.open('POST', 'my-script.php');
req.send(fd);
});
This works perfectly. However, on the PHP side, when I run print_r($_FILES), the mime type is ending up as text/plain. I'd like to submit to PHP the mime type, so I can check this before allowing the file through (I'm aware mimetype is not always reliable, but it's just another check of several I'm doing.)
I added this to the AJAX request:
req.setRequestHeader('Content-Type', 'video/webm');
However with this added, the PHP script reports that $_FILES is completely empty.
How can I submit the mime type along with the file?
The formData.append() as a 'filename' field. See:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
What would happen if you gave it a name like 'myMovie.webm'? It's worth a try, I think. So:
fd.append('file', resolution_data[0]);
would become:
fd.append('file', resolution_data[0], 'myMovie.webm');
I haven't tested this at all, it's just a suggestion.
Since you haven't reacted yet, I read a bit more. I also found this:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
in it they use this code:
var content = '<a id="a"><b id="b">hey!</b></a>';
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
Note the mime type! That looks very promising!

Converting data of content type 'application/java-archive' into blob object

I have one GET request which returns a JAR file, which I need to download.
Easiest way to to the downloading part is to let browser handle the downloading part as follows :
window.location.href = URL
But, that does not work for error handling (handling server errors).
Alternatively, I found another way which creates blob object, and creates Object URL from that object and assigns it to anchor tag for downloading -
callSomeURL().then((res) => {
const blob = new Blob([res._body], { type: res.headers.get('content-type')
});
const url = window.URL.createObjectURL(blob);
const linkElement = document.createElement('a');
linkElement.setAttribute('href', url);
linkElement.setAttribute('download', 'test jar file');
const clickEvent = new MouseEvent('click', {view: window});
linkElement.dispatchEvent(clickEvent);
}).catch((error) => error handling part)
content type is 'application/java-archive'
res._body is encoded string.
Problem with this is that the file downloaded is invalid / corrupt. (Not sure whats wrong with the implementation).
I have 2 questions here -
What is the proper way to create a blob object? Is it created using the encoded data that the response returns or the URL of the request?
What is the proper way to handle file download with error handling?
Your problem is that the response you get is plain/text.
So when you generate your Blob, it's still plain text, and the binary data got mangled when converted to utf16 by javascript.
To avoid that, you can request it as a blob directly from your ajax call.
With XMLHttpRequest, you can set the responseType parameter of your XHR object:
var xhr = new XMLHttpRequest();
xhr.open('get', your_url);
xhr.responseType = 'blob';
xhr.onload = function() {
var blob = xhr.response;
// do something with the blob
var url = URL.createObjectURL(blob);
anchor.href = url
anchor.click();
};
xhr.send();
With fetch API, you can call the blob() method of the Response object
fetch(your_url)
.then(resp => resp.blob())
.then(doSomethingWithBlob)

Can't send file using XMLHttpRequest

The code is simple and it works when I append a string to the FormData:
var data = new FormData();
data.append('String', stringVar);
var request = new XMLHttpRequest();
request.open('POST', 'upload.php');
request.send(data);
But if I append a file to the FormData (data.append('File', fileVar);) I get a 503 response.
The problem doesn't happen when I'm running the code on localhost, so I know there's no problem with the code and it's from the server. Maybe I should change some PHP or Apache settings on the server, I don't know.
Any help or comments would be appreciated.

Categories

Resources