FormData Inserting Extra TExt - javascript

I'm using form data in Javascript to send my inputs to the server but I noticed something funky. In Firefox and Chrome it sends back extra text along with the data and adds it to the original value. Here is an example of what chrome outputs
------WebKitFormBoundaryq5GElQTvd3mbU5qE--
Here is my code. I am doing a PUT request.
var formData = new FormData();
formData.append('user','tester');
var req = new XMLHttpRequest();
req.onload=function(e){
console.log(this)
}
req.open('PUT','http://localhost/site_template/create_file.php',true);
req.send(formData);

Related

Attach a file to an input with javascript

I have an input to upload files
<input type="file" name="comment[video_file]" id="comment_video_file">
Is it possible to attach a file by JavaScript?
I have tried but it didn't work
let file = new File([videoBlob], "video.mp4", { type: "video/mp4" });
let element = document.getElementById("comment_video_file");
element.append("video", video);
If I console log the element after the append it looks like this
<input type="file" name="comment[video_file]" id="comment_video_file">
"video"
"[object File]"
</input>
It isn't possible to create a file and attach it to an HTML form input but using the FormData object you could send a generated file to the server as part of a post request.
Pulled from the MDN:
var formData = new FormData();
// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
Which should get you the same result of a file generated by JS sent to the server.
MDN article on file inputs states:
You can set as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57
I tried setting input.files to a files property from a drag-n-drop files event and it worked. Though I'm not sure if it's possible to do it with a manually created File.
If this won't work, try sending an XMLHttpRequest with FormData with a file Blob, as advised in other answers/comments.

Formdata image file isn't being caught by API call

I am using JavaScript to create an API call and send it to a corresponding Asp.Net Core function.
JavaScript:
function fileSubmit() {
var data = document.getElementById("myFile").files; //it should be noted that this successfully catches the file.
var formData = new FormData();
formData.append("files", data);
var url = "http://localhost/api/Surveys/123456/Units/987654/Images";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "image/jpeg");
xhr.send(formData);
}
.Net Core:
[HttpPost]
[Route("{Id:int:min(1)}/Units/{unitId:int:min(1)}/Images")]
[ProducesResponseType(typeof(IAPIResponse2<UploadImagesResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(IAPIResponse2<UploadImagesResponse>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UploadImages([FromForm, Required] IList<IFormFile> files)
{
//do stuff
}
I am able to create and send the API call and it is caught by the Asp.Net function, but the files parameter is empty. The file list is successfully appended to the formData object in the JavaScript function, as far as I know.
What am I missing?
There are two problems with your JavaScript code above:
files is being sent incorrectly. If you look at the request, you'll see it's a bit confused and includes [object FileList] as part of the body.
To solve this issue, you'll want to iterate through the files and add them individually:
var files = document.getElementById("myFile").files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("files", files[i]);
}
If you are just sending the one file, you could simplify this:
var files = document.getElementById("myFile").files;
var formData = new FormData();
formData.append("files", files[0]);
You should not set the Content-Type header when making the request.
To solve this issue, simply remove your call to setRequestHeader. The Content-Type header will be set by the XHR process to be multipart/form-data with boundaries (see the RFC for the Multipart Content-Type).
Each part starts with an encapsulation boundary, and then contains a body part consisting of header area, a blank line, and a body area.
Due to the way this is structured, the Content-Type is specified on a per-file basis. If you are interested, have a look at the request in the developer tools once you've made the changes I have detailed.

Not sending XmlHttpRequest with only one parameter called "id"

I'm new to javascript. If I try to run this piece of code, the request doesn't gets sent.
function getObjectData(objectId)
{
var url = "FMDiag/getObjectData?id=" + objectId;
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("GET", url, true);
xmlHttpRequest.onload = function(e)
{
...
};
xmlHttpRequest.send();
}
If I change ?id= to something else, e.g. ?objectId=, the function works as expected.
Or if I add additional parameters to the request, it works again.
Strange though, ?id= works from form data sending.
Any ideas?

How to send image from html page to the server dynamically

How can I send a dynamically-created image from a JSP page to the action class using Javascript or jQuery-AJAX?
I need to send the image file as a file upload with Multipart/form-data.
You are allowed to make mutlipart/form-data requests with AJAX. Just gather the image binary and send it as such.
Update: based on the sample code you posted:
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "site", true);
var formData = new FormData();
formData.append(myimg);
xmlHttp.send(formData);
Make sure you're using the API correctly. .append takes two arguments
formData.append("myimg", myimg);

Use XPCOM to upload file/image on webpage

I am using an example found here. Mozilla developers
I am interested in this example.
function upload(postUrl, fieldName, filePath)
{
var formData = new FormData();
formData.append(fieldName, new File(filePath));
var req = new XMLHttpRequest();
req.open("POST", postUrl);
req.onload = function(event) { alert(event.target.responseText); };
req.send(formData);
}
But I can't understand what goes where on this example. filePath is understandable but postUrl , fieldName I can find. I am working on image uploading on the page that has Drag and Drop zone for image uploading. How can I use this function to upload the image on my website?
Check out the FormData documentation and XMLHttpRequest documentation.
fieldName The name of the (form) field whose data is contained in value.
postUrl The URL to which to send the request.
You should have a server-side endpoint that responds to the upload request.
For example:
upload('http://mysite.com/uploader.php', 'fileField', 'path/to/my/file.jpg');
Then if you are using PHP on the server-side; you can access that field value on the server-side like this:
$my_files = $_FILES['fileField'];

Categories

Resources