Uploading xlsx file via Javascript to c# API - javascript

I am trying to upload am xlsx file via Javascript to a C# API.
Whenever I call the 'send' below, I get:
A 'Bad Request' response if I leave 'Content-Type' in the header; or
An 'Unsupported Media Type' response if I remove it.
I have looked over numerous articles about how to solve this but nothing has worked.
Javascript function
function uploadFile(file, i) {
var url = "API POST Route";
var xhr = new XMLHttpRequest();
xhr.open("post", url, true);
// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
//edited with solution from https://stackoverflow.com/questions/6211145/upload-file-with-ajax-xmlhttprequest
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
}
UPDATE
Edited original solution to include FormData() but still getting same errors

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

Upload and send string as file via telegram bot

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);

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!

XHR file upload failing with net::ERR_FILE_NOT_FOUND

I'm building a "chunked" file upload using simple XHR requests in an angularjs environment. After a random amount of time or uploaded chunks all upload-requests fail in chrome. The xhr.onerror outputs an "net::ERR_FILE_NOT_FOUND" error.
Following suggestions from other posts I disabled all chrome extensions but nothing changed.
var formData = new FormData();
formData.append('data', blob);
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.upload.onload = function(res) {
//success
}
request.upload.onerror = function(error) {
//error
};
request.send(formData);
Other posts also suggested a connection to the uploaded file size (between 200-500mb) but the used chunk-size is only 1 mb.
Anybody else experienced problems like that?

Angular JS POST vs regular XHR

Trying to upload an image using angular's $http.post()
I'm setup like this, where file is the first file from the file input.
var fd = new FormData();
fd.append("content", file);
fd.append("binary", true);
Running this uploads the file properly:
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(){alert("Done!");}, false);
xhr.open("POST", path);
xhr.send(fd);
But I want to use angulars $http. So I do this and it isn't uploaded properly:
$http({
method: 'POST',
url: path,
data: fd
});
What am I missing? I've tried setting the headers to multipart and still no dice.

Categories

Resources