I am trying to attach a file and upload through ajax request. But it creates a new file instead of uploading the file I am trying to provide.
var formData = new FormData();
var blob = new Blob([JSON.stringify({})], {type : 'application/json'});
formData.append("file", blob, "sample.txt");
When I open the file I can see the content getting replaced with {}
Code mentioned will only create and empty form object. If you need to upload that form object to server, use following similar code.
var formElement = document.querySelector("form");
var formData = new FormData(formElement); //reads user input data from form
/**var blob = new Blob([JSON.stringify({})], {type : 'application/json'}); //added {} to form
formData.append("file", blob, "sample.txt"); //names file and keeps {} as content ----not needed**/
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php"); //put ypur end point here
request.send(formData); //send to server
your form html should look something like this
<form enctype="multipart/form-data" method="post" name="submitform">
<label>File to upload:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
Please read more on this here
Related
Form
<h2 class="uk-modal-title">Change Profile Picture</h2><br>
<form action="{{url_for('upload_dp', username=username)}}" method="POST" enctype="multipart/form-data">
<input type="file" accept="image/*" placeholder="Upload profile picture" onchange="loadFile(event)" id="uploaded" required>
<img id="dp">
<button onclick="beforeSubmit()">Upload</button>
Javascript
var cropper;
function loadFile(image) {
var dp = document.getElementById('dp');
dp.src = URL.createObjectURL(image.target.files[0]);
dp.onload = function() { URL.revokeObjectURL(dp.src)};
cropper = new Cropper(dp, { aspectRatio: 1 });
}
function beforeSubmit() {
cropper.getCroppedCanvas().toBlob((blob) => {
var formData = new FormData();
formData.append("dp", blob);
formData.append('username', '{{username|safe}}');
var xhr = new XMLHttpRequest;
xhr.open( "POST", "/upload_dp");
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formData);
}, "image/jpeg");
}
When an image is uploaded for , it renders and a cropper appears on it. Till here, things work fine.
User, changes cropper according to his need and on pressing button Upload, function beforeSubmit runs where the problem lies. I do not receive any files in the flask application. The request below has non-empty stream and I receive the argument username, but the file dp having cropped image as blob is not received! Please help.
print(request.__dict__)
Is stream the blob file? How are xmlhttprequest with files seen in flask?
I have a JSP page with <form> that uploads a file on submit.
But the upload function is not uploading any file to the server at the path /uploads.
HTML form:
<form action="./index.jsp" onsubmit="uploadFile()">
<input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
<button type="submit" class="btn btn-primary">Run Profiling</button>
</form>
Javascript function to upload file:
<script>
function uploadFile(){
let excel = document.getElementById("excelInput").files[0]; // file from input
alert(excel);
let req = new XMLHttpRequest();
let formData = new FormData();
try{
formData.append("excel", excel);
req.open("POST", 'D:\\eclipse\\workspace\\Project2\\WebContent\\uploads');
req.send(formData);
}
catch(e){
alert(e);
}
}
</script>
It is not going to the catch() section. But it isn't uploading either.
Is there anything missing ?
The dupes seems to be very poor, so I post an answer.
You basically want to add an eventListener AND submit to a WEB SERVICE! Not a file location
window.addEventListener("load", function() {
document.getElementById("uploadForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop the submit
let excel = document.getElementById("excelInput").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
try {
formData.append("excel", excel);
req.open("POST", 'actual web address of a process that can handle xmlhttprequests');
req.send(formData);
} catch (e) {
console.log(e);
}
})
})
<form action="./index.jsp" id="uploadForm">
<input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
<button type="submit" class="btn btn-primary">Run Profiling</button>
</form>
I want to convert a blob URL AKA (window.URL.createObjectURL(blob);) into a file object so I can use it with FormData() so I can use that as an upload image file for AJAX but I am not able to do that successfully and I can't find a way to make the blob URL into a file
object for my code situation and I know its possible to do this according to the posts I visited on here it can be done here's one of posts that claim that you can do that How to convert Base64 String to javascript file object like as from file input form? but the reason why I'm not using any of those posts methods because I don't know how to integrate their methods to my code situation or its too complicated to understand.
This is my code that I been working on.
index.php
<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelector('#image-input').addEventListener('change',createABlobUrlForAImgSrcAndUseThatAsAFileUploadFile);
function createABlobUrlForAImgSrcAndUseThatAsAFileUploadFile(){
//Creating a blob URL
var image_input = document.querySelector('#image-input').files[0];
var file_type= image_input.type;
var blob = new Blob([image_input], { type: file_type || 'application/*'});
var blob_url= window.URL.createObjectURL(blob); //<-Example blob:http://localhost/ed6761d2-2bb4-4f97-a6d8-a35c84621ba5
//
//Form data
var formData= new FormData();
formData.append('blob_url', blob_url);
//
//<AJAX>
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
if(xhr.readyState == 4){
document.querySelector('#output').innerHTML= xhr.responseText;
//<Allow JS in AJAX request>
var exJS= document.querySelectorAll('#output script');
var enableAll= exJS.length;
for(var i=0; i < enableAll.length; i++){
eval(exJS[i].text);
}
//</Allow JS in AJAX request>
}
}
xhr.open('POST','x');
xhr.send(formData);
//</AJAX>
}
});
</script>
<input id='image-input' type='file'>
<div id='output'></div>
x.php
<?php
$file=$_FILES['blob_url']['name'];
$location='images/'.$file;
move_uploaded_file($_FILES['blob_url']['tmp_name'],$location);
?>
I know my code is not logically correct and I will have to change my code to be able to do what I want to do so I am aware it is not logically correct. Just trying to show you guys what I mean.
This is how I got it done in my project. But in my case, I wanted to convert a blob to a wav file and then send to the back-end.
//Save your blob into a variable
var url = URL.createObjectURL(blob);
//Now convert the blob to a wav file or whatever the type you want
var wavefilefromblob = new File([blob], 'filename.wav');
//Pass the converted file to the backend/service
sendWavFiletoServer(wavefilefromblob);
//This is my function where I call the backend service to send the wav file in Form data
function sendWavFiletoServer(wavFile) {
var formdata = new FormData();
formdata.append("file", wavFile);
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "https://yourserviceurl/api/");
ajax.setRequestHeader('API_SECRET', UzI1NiIsInR5cCI6IkpXVCJ9eyLCJleHAiO');
ajax.send(formdata);
}
I think uploading form data should be a blob object, not a blob URL
javascrip:
var image_input = document.querySelector('#image-input').files[0];
var blob_url= window.URL.createObjectURL(image_input);
//Form data
var formData= new FormData();
// ...
// here , content-type: multipart/form-data
formData.append('upload_file', image_input);
php:
$file=$_FILES['upload_file']['name'];
$location='images/'.$file;
move_uploaded_file($_FILES['upload_file']['tmp_name'],$location);
I had the same question and found a way.
This will give you a Blob object:
let blob = await fetch(url).then(r => r.blob());
I need some help for my problem. I want to delete some files from a FileList and then send them via Ajax with new FormData. For this I only want to work with Javascript.
After the files have been selected by users, they are evaluated by the content_evaluate () function and the files to be sent are assigned to a new array transfer_files[]. These files are added to a new formdata and then sent.
However, all files from the origin input are sent even if only the modified array is given to the new formdata. e.g. 3 of 5 files have to be sent.
<form id="formular" onsubmit="send_data();" method="post"
enctype="multipart/form-data">
<table id="dyninfo" align="center" border="1">
<tr>
<td>
<input id="upload_filename_id" name="upload_filename" type="file"
onchange="content_evaluate();" size="60" multiple>
</td>
<td>
<button type="submit" id="upload" style="width:120px">Upload</button>
</td>
</tr>
</table>
</form>
Script:
var transfer_files = [];
function send_data()
{
var formData = new FormData();
for (var i = 0; i < transfer_files.length; i++)
{
var file = transfer_files[i];
formData.set(transfer_files, file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.html', true);
xhr.send(formData);
return false;
};
You were looping through a 0 length array ( transfer_files )
What you should have done instead:
Use the input file object to retrieve the inputted files, then you can loop through it
var inputFile = document.querySelector('#upload_filename_id'),
transfer_files = inputFile.files;
function send_data()
{
var i, file, formData = new FormData();
for ( i = 0; i < transfer_files.length; i++ )
{
file = transfer_files[ i ];
formData.set( inputFile.name, file, file.name );
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.html', true);
xhr.send(formData);
return false;
};
Hello I want to use pure javascript ajax (no jquery) to append formdata but I don't know how to get data from input file type
function handleForm(e)
{
e.preventDefault();
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username);
data.append('email', email);
data.append('file', ?????); ////// How to get data from input file
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test2.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
...
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Image: <input type="file" name="file" id="myimg"><br/>
<input type="submit">
</form>
The <input type="file" /> HTML element has a files property (of type FileList).
Check the length if a file has been selected and if so add the file(s) to the FormData object
var fileInput = document.getElementById("myimg");
if (fileInput.files.length > 0) {
data.append("file", fileInput.files[0]);
}
For more examples on how to use the FormData object check this link:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
document.getElementById("file_input_id").files[0]
try
<input type="file" id="fileinput" />
to get file.. you can use
var myFile = $('#fileinput').prop('files')[0];