How to get a file from a url that contains a csv but my link does not contain the filename.
example: https:/api/download
This link download the csv file automatically and saves it.
How can I get the contents csv using the url but the csv automatically downloads and display the data in html code below doesnt work
<script type="text/javascript">
function getCSV(func) {
var file = "https:/api/download";
var rawFile = new XMLHttpRequest();
var allText;
rawFile.open("GET", 'API.csv', false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4)
if(rawFile.status === 200 || rawFile.status == 0)
allText = rawFile.responseText;
if(func!=undefined && typeof(func) == "function"){
func(allText);
}
};
rawFile.send();
}
getCSV(function(contents){
alert(contents);
})
Related
I have an external json file and I would like to access the data from it in my javascript file or my html file. I've tried looking at other solutions but its not working, I don't have jQuery so please don't include it.
What I would like for this to do is load the json file and then display the contents on the web page.
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'PATIENT5.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function callback(data)
{console.log(data);
}
PATIENT5.json
["Harry","35"]
I tried adding the console.log(data); but when I checked the console there wasn't anything there. Anything would be helpful this is my first time using javascript/html! Thanks!!
Add the code with script tag. and call the function.
<script type="text/javascript">
function loadJSON(file, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
//usage:
loadJSON("file.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
</script>
I'm trying to upload and download the excel file in a single click operation. I'm calling two APIs in a single operation. The download operation is working fine. But during file upload, an empty excel file is being uploaded with the exact file-name. This is the server side code
Excel Duplicates Remover in JAVA. The server-end works fine. And this is the client-side code.
<!DOCTYPE html>
<html>
<body>
Select a file: <input type="file" id="file" accept=".csv, .xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" multiple size="50"/><br>
Keyword:<input type="text" id="columnHeading"/><br>
<button type="button" onclick="downloadDoc()">Request data</button>
<script>
function downloadDoc(){
var fileTab = document.getElementById("file");
var columnHeading = document.getElementById("columnHeading");
if('files' in fileTab) {
if(fileTab.files.length == 1) {
var url = 'http://localhost:8080/excel-duplicate-remover/rest/fileService/';
var uploadUrl = url + "upload";
var file=fileTab.files[0];
var formData = new FormData();
formData.append("columnHeading",columnHeading);
formData.append("file",file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var path = response.path;
var downloadUrl = url + 'downloadFile?fileName=' + path;
downloadFile(downloadUrl);
}
};
xhr.open("POST", uploadUrl);
xhr.send(formData);
}else{
console.log("file not present");
}
}
}
function downloadFile(filename) {
console.log("filename"+filename);
var link = document.createElement('a');
// Add the element to the DOM
link.setAttribute("type", "hidden"); // make it hidden if needed
link.href = filename;
link.download;
document.body.appendChild(link);
link.click();
link.remove();
}
</script>
</body>
</html>
Why is the file being uploaded as an empty excel file?
I'm trying to make javascript read a .txt file that contains links to websites, and with that can I press a button to get sent to a random website.
But my code won't work, I have tried a lot of things...
Here is my code
<script>
var sites = [];
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
callback(allText);
}
}
}
rawFile.send(null);
}
readTextFile("file:../Nicklas Behrend/Desktop/links.txt", filesText =>{
sites = filesText.split('\n');
});
function randomSite() {
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}
</script>
At this part it says
expression statement is not assignment or call
readTextFile("file:../Nicklas Behrend/Desktop/links.txt", filesText =>{
sites = filesText.split('\n');
});
When I press the button that I made, I get to a site that says "404 not found"
You cannot access file protocol (file:) using XMLHttpRequest.
Meaning the file you are trying to access must be uploaded to a server and get the path (e.g., http://...) before you can get it through XMLHttpRequest.
i am using javascript to upload an image using the unsigned mode. the resultant image is a blank image or i can say an image filled with black color. not sure what is wrong. the code looks like follow:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { //Call a function when the state changes.
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
} else {
alert("Error dude: " + xhttp.statusText);
}
}
var parameters = {
"file": imgData,
"upload_preset": "mycode"
};
xhttp.send(JSON.stringify(parameters));
resultant image is:
http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg
Please note that imgData is base64 encoded
You need to use FormData for uploading the file:
const cloudName = 'your cloud name';
const unsignedUploadPreset = 'your unsigned upload preset';
// Upload base64 encoded file to Cloudinary
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....');
// *********** Upload file to Cloudinary ******************** //
function uploadFile(file) {
var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`;
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
// File uploaded successfully
var response = JSON.parse(xhr.responseText);
// https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg
var url = response.secure_url;
// Create a thumbnail of the uploaded image, with 150px width
var tokens = url.split('/');
tokens.splice(-2, 0, 'w_150,c_scale');
var img = new Image(); // HTML5 Constructor
img.src = tokens.join('/');
img.alt = response.public_id;
document.body.appendChild(img);
}
};
fd.append('upload_preset', unsignedUploadPreset);
fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary
fd.append('file', file);
xhr.send(fd);
}
See full example here. It will upload a small Michael Jordan jumpman image to your account.
I'm not very practiced in using XMLHttpRequests, but I am working on a drag and drop file converter that takes a zip file and returns one in response. Most of it is working, but I'm not sure how to pick the zip file out of the response. Here's where I'm at:
dropZone[0].ondrop = function(event) {
// Stop the browser from opening the file in the window
event.preventDefault();
dropZone.removeClass('hover');
// Get the file and the file reader
var file = event.dataTransfer.files[0];
// Send the file
var xhr = new XMLHttpRequest();
// xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.onreadystatechange = function(response) {
if (event.target.readyState == 4) {
alert("winner");
if (event.target.status == 200) {
$('#dropZone').text('Upload Complete!');
}
else {
dropZone.text('Upload Failed!');
dropZone.addClass('error');
}
}
};
xhr.open('POST', 'Home/handleFileUpload', true);
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
};
fiddler is showing a 200 with some binary results. How do I make the browswer save/download it as a zip?