Hi I am trying to read the csv file (just on front end not want to store it on back end ). The error I am getting is attached with the image below.
enter image description here
The code I am trying is.
function file(){
var fullPath = document.getElementById('upload').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
alert(filename);
// passFile(filename);
d3.csv(filename, function(error, data) {
if (error) throw error;
console.log(data); // [{"Hello": "world"}, …]
});
}
}
I just want to read the data from file but getting this error.
I have tried other ways too like This method I tried first but does not work for me. Can anyone help me out?
d3.csv() function is for fetching csv file from a remote location. If you want to read a local file by <input type="file"> element, you should use FileReader to read the file by yourself and parse it with d3.csvParse() function.
For example:
function file(){
var uploadFileEl = document.getElementById('upload');
if(uploadFileEl.files.length > 0){
var reader = new FileReader();
reader.onload = function(e) {
console.log(d3.csvParse(reader.result));
}
reader.readAsText(uploadFileEl.files[0]);
}
}
<input type="file" id="upload" />
<button id="upload" onclick="file()">Read CSV</button>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.1/d3.min.js"></script>
Related
What I am trying to do : I have a cloud page where the user can upload CSV file. When user clicks on the “upload” button the a function called getBase64() is called (please refer the below code). The getBase64() function will encode the uploaded file and post it to a second cloud page.The second cloud page then takes the posted data.
Note: I am trying to adapt this solution to my need (csv file) by referring to this article partially https://sfmarketing.cloud/2020/02/29/create-a-cloudpages-form-with-an-image-file-upload-option/
What’s the problem : When I try to click the the “upload” button the page is not taking me to the second CloudPage. Please could anyone let me know what I am doing wrong here ?
Here is the code:
CloudPage 1
<input id="file" type="file" accept=".csv">
<br>
<button id="button">Upload</button>
<script runat="client">
document.getElementById("button")
.addEventListener("click", function() {
var files = document.getElementById("file").files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
//prepare data to pass to processing page
var fileEncoded = reader.result;
var base64enc = fileEncoded.split(";base64,")[1];
var fullFileName = document.getElementById("file").files[0].name;
var fileName = fullFileName.split(".")[0];
var assetName = fullFileName.split(".")[1];
fetch("https://cloud.link.example.com/PAGE2", { //provide URL of the processing page
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
base64enc: base64enc,
fileName: fileName,
assetName: assetName
})
})
.then(function(res) {
window.alert("Success!");
})
.catch(function(err) {
window.alert("Error!");
});
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
</script>
CloudPage 2
<script runat="server">
var jsonData = Platform.Request.GetPostData();
var obj = Platform.Function.ParseJSON(jsonData);
</script>
I do not see any errors in the code and when I click on the upload button I get a success message but it does not take me to the second page. Please can anyone guide me how to retrieve this posted data in second page as I am not able to get the encoded data in page 2?
I want to upload a json/shp/kml/kmz file and convert it into geojson.
HTML
<input type="file" name="uploadfile" accept=".json,.geojson,.shp,.kml,.kmz" id="file_loader" hidden>
<input type="text" id="upload_name" placeholder="Name" aria-label="Name" >
Javascript
var jsonObj;
var fileExt = upload_name.split('.').pop(); // Get file extension
var reader = new FileReader(); // Read file into text
reader.readAsText($('#file_loader')[0].files[0]);
reader.onload = function(event) {
if (fileExt == 'geojson') {
jsonObj = JSON.parse(event.target.result); // Parse text into json
} else if (fileExt == 'shp') {
// how to convert event.target.result to geojson?
} else if (fileExt == 'json') {
//
} else if (fileExt == 'kml') {
//
} else if (fileExt == 'kmz') {
//
}
}
function addToMap(){
// This function add jsonObj as a layer to Mapbox
// No problem here
}
I've tried using
https://www.npmjs.com/package/gtran
by npm install gtran and then var gtran = require('gtran'); in my javascript file, but it gives me an error:
Could not find a declaration file for module 'gtran'
gtran doesn't have a #types/gtran.
My javascript file gets processed by webpack with babel-loader. Not sure if that has anything to do with the error.
Even if I successfully include gtran, its functions need filename as argument. My data is in a string and not a file, I don't have a filename. What do I do? Do I save the string in a file and then gtran that file?
You can't use var gtran = require('gtran'); in your frontend javascript file. It is used in Node.js.
However, you can use it with the aid of an extension like Browserify. See this post for more details.
I've written a d3 script that plots some data and in which the path to the input file is hard coded.
I'd like to be able to select the file by browsing on my computer and then passing it to the script.
<body>
<!--locally browse to get the filename-->
<input type="file" id="input">
<script src="http://d3js.org/d3.v3.js"></script>
<script>
// Get the data
d3.tsv("#input", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// then the code that plots etc....
</script>
</html>
1) Create the input select button and register it to a file select handler function:
var input = d3.select("body").append("input")
.attr("type","file")
.on("change", handleFileSelect)
2) The file select handler will register a new function with the fileHandler as input on the onload callback:
// Single file handler
function handleFileSelect() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
var f = event.target.files[0]; // FileList object
var reader = new FileReader();
reader.onload = function(event) {
load_d3(event.target.result)
};
// Read in the file as a data URL.
reader.readAsDataURL(f);
}
3) Crete a function with a fileHandler as input, that calls your D3 code (d3.json in this example. You can adapt it for tsv)
function load_d3(fileHandler) {
d3.json(fileHandler, function(error, root) {
//do stuff
};
};
Hope this helps.
Subscribe to input file change event. Then use FileReader to get content of selected file, then parse it using d3.tsv.parse
You can use d3.csvParse to parse the result after reading file. Here's my working code:
<input type="file" id="input" onchange="handleFiles">
<script>
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
var file = fileList[0];
var reader = new FileReader();
reader.onload = function(e) {
// The file's text will be printed here
console.log(e.target.result);
console.log(d3.csvParse(e.target.result));
};
reader.readAsText(file);
}
New to javascript, having trouble figuring this out, help!
I am trying to use the Javascript FileReader API to read files to upload to a server. So far, it works great for text files.
When I try to upload binary files, such as image/.doc, the files seem to be corrupted, and do not open.
Using dojo on the client side, and java on the server side, with dwr to handle remote method calls. Code :
Using a html file input, so a user can select multiple files to upload at once :
<input type="file" id="fileInput" multiple>
And the javascript code which reads the file content:
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
// fileContent object contains the content of the read file
};
})(this.filesToBeUploaded[i]);
reader.readAsBinaryString(this.filesToBeUploaded[i]);
}
}
The fileContent object will be sent as a parameter to a java method, which will write the file.
public boolean uploadFile(String fileName, String fileContent) {
try {
File file = new File("/home/user/files/" + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileContent.getBytes());
outputStream.close();
} catch (FileNotFoundException ex) {
logger.error("Error uploading files: ", ex);
return false;
} catch (IOException ioe) {
logger.error("Error uploading files: ", ioe);
return false;
}
return true;
}
I have read some answers suggesting the use of xhr and servlets to achieve this.
Is there a way to use FileReader, so that it can read files of any type (text, image, excel etc.) ?
I have tried using reader.readAsBinaryString() and reader.readAsDataUrl() (Decoded the base64 fileContent before writing to a file), but they did not seem to work.
PS :
1. Also tried reader.readAsArrayBuffer(), the resultant ArrayBuffer object shows some byteLength, but no content, and when this is passed to the server, all I see is {}.
This bit of code is intended to work on only newer versions of browsers..
Thanks N.M! So, it looks like ArrayBuffer objects cannot be used directly, and a DataView must be created in order to use them. Below is what worked -
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
var int8View = new Int8Array(fileContent);
// now int8View object has the content of the read file!
};
})(this.filesToBeUploaded[i]);
reader.readAsArrayBuffer(this.filesToBeUploaded[i]);
}
}
Refer N.M 's comments to the question for links to the relevant pages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
//here ajax
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>
I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server