So here's the thing: I have a file generate by a random application on my pc. The application can edit the file at random time, without any warning. I need to send the file to my server in a periodic manner, (like every 5 or 30 seconds). Before that I used a little cURL script, but since I often need to make this process from different workstations, I thinked to create a little page with a select input and a button that starts this function:
var syncFunc = function(){
var reader = new FileReader();
reader.readAsText($("#file")[0].files[0]);
reader.onload = function() {
var datas = reader.result;
$.ajax({
url : 'callback',
type : 'POST',
data : {"data" : datas},
success : function(data) {
//do stuff
},
complete : function(data){
syncTimeout = setTimeout(syncFunc, 5000);
}
});
};
};
when I start the script it all goes well, until the file get changed by the application: sometimes (not always) FileReader throws a DOMException NotReadableError and reader.result contains null. The file can be read again without problem if I reselect it from the input, but if I don't do so, any subsequent tentative of reading it fails. And what bugs me more is that this happens in a actually random manner, where the same edit of the file selected sometimes does e sometimes does not generate the error.
Also, if I try to send the file using a FormData, the file is read and sent (as I can check using the Inspector and checking the HTTP request made), but the server throws the error "upload not completed")
Any idea?
Related
Currently, I'm developing a WebService which user selects a file and we're doing some pre-processing on user's browser later we will send the file to the server.
When a user selects a file from file manager(<input type=file id="dropzone"/>) an event will fire and will load the selected file using FileReaderAPI, when the process is done(it's guaranteed that this section will execute after the first process finished) when I want to read the file again later in the service using document.getElementById("dropzone") it returns the null.
here is the code for the input component, in this case, I'm using react-dropzone.js:(since I'm accessing input element by getElementById it makes no difference which library is used)
const{
acceptedFiles
} = useDropzone({
accept: "video/*, .mkv",
onDrop: files => props.handle()
});
return(<div> <input {...getInputProps()} id="dropzone"/> </div>) ;
props.handle(files) refer to the function which will be doing the file processing
following is a part of handle() function which deals with the selected file and will fire when a user selects a file.
var upFile = document.getElementById("dropzone");
var file = upFile.files[0];
//Original function iterate over all slices
var r = new FileReader();
var blob = file.slice(offset, length + offset);
r.onload = processChunk;
r.readAsArrayBuffer(blob);
Later when I want to access the file again using document.getElementById("dropzone") it returns null
Any Idea for solving this?
After many trials and errors, I found out this is caused by one of the browser's 3rd party security extensions.
Make sure to disable these kinds of extensions in the developing stage.
I want to use a button, instead of this input box to load the text file. When I press the button, I want to load a text file called "me.txt" without showing a browse window. ("me.txt" is in the same path). Is there anyway to do that?
<input type="file" name="file" id="file">
<script>
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
var wordStr = (lines[line]);
var index = wordStr.indexOf("="); // Gets the first index where a space occours
var word = wordStr.substr(0, index); // Gets the first part
var meaning = wordStr.substr(index + 1);
if (word=="a") {
document.write(meaning);
}
}
};
reader.readAsText(file);
};
</script>
You cannot read a file from the user's computer without the user actively picking the file; and you cannot know the real path of that file on the user's computer. Browsers quite rightly prevent both of those things.
When I press the button, I want to load a text file called "me.txt" without showing a browse window. ("me.txt" is in the same path).
If you mean that me.txt is a file that's on the same path as the HTML page this code is running in, then:
If you're using a web server process and accessing the page via http:// or https://, you can use a simple ajax request to read the file, for instance:
$.get("me.txt").then(function(data) {
// ...use data...
});
If you're just running from the local file system (a file:/// URL), it's much better to use a local web server process instead. But if you have to use a file:/// URL, you can't read other local files in Chrome, but you can in Firefox:
// NOT allowed from file:/// URLs not work in Chrome; is allowed in Firefox
$.ajax({
url: "test.json",
dataType: "text"
}).then(function(data) {
// ...use data here
});
Firefox will report an XML parsing error in the console, but will also give you the data.
I'm working on Audio/Video upload and Task. Can somebody help me show to achieve this functionality in Angular JS?
We would need more details, what hae you tried, what type of backend (REST, SOAP, Web Service in general) you are using, in which language...
I did it with a Java RESTful server by, probably, not the smarter solution.
$scope.uploadVideo = function(){
// Obtaining the selected file. In case of many, the others will be from the position 1 of the array
var f = document.getElementById("videoInput").files[0];
console.log("====================>SIZE: "+f.size);
var name = f.name;
//Getting the file name and its extension
}
//Loading the file and passing the callback as a parameter
loadFile(f, function(data){
// The file consist on its name and bytes
var file={
name:name,
data:data
}
//Sending the video
servicioRest.postFile(file)
.then(function(){
//Whatever
})
.catch(function(err){
console.log("ERROR");
alert("ERROR: "+err);
});
});
};
//---------------------------------------------------- UTILS ----------------------------------------------
function loadFile(source, callBack){;
var r = new FileReader();
//Event that will be triggered when FileReader finish reading the file
r.onloadend = function(e){
var data = e.target.result;
// some chars cannot be sent through http requests. So we encode them in base64 to ensure we send the correct bytes
data=btoa(data);
console.log(data.length);
callBack(data);
//send you binary data via $http or $resource or do anything else with it
}
//Reading the file. When it ends, the event "onloadend", previously declared, will be triggered
r.readAsBinaryString(source);
}
Then, in the server, I decoded the bytes and create a file with them and that bytes... or save them in the database.. Whatever you want.
But I insist, we need more details to answer you correctly. It's impossible, at list for me, to answer you correctly with only that information
I'm making a JavaScript script that is going to essentially save an old game development sandbox website before the owners scrap it (and lose all of the games). I've created a script that downloads each game via AJAX, and would like to somehow upload it straight away, also using AJAX. How do I upload the downloaded file (that's stored in responseText, presumably) to a PHP page on another domain (that has cross origin headers enabled)?
I assume there must be a way of uploading the data from the first AJAX request, without transferring the responseText to another AJAX request (used to upload the file)? I've tried transferring the data, but as expected, it causes huge lag (and can crash the browser), as the files can be quite large.
Is there a way that an AJAX request can somehow upload individual packets as soon as they're recieved?
Thanks,
Dan.
You could use Firefox' moz-chunked-text and moz-chunked-arraybuffer response types. On the JavaScript side you can do something like this:
function downloadUpload() {
var downloadUrl = "server.com/largeFile.ext";
var uploadUrl = "receiver.net/upload.php";
var dataOffset = 0;
xhrDownload = new XMLHttpRequest();
xhrDownload.open("GET", downloadUrl, true);
xhrDownload.responseType = "moz-chunked-text"; // <- only works in Firefox
xhrDownload.onprogress = uploadData;
xhrDownload.send();
function uploadData() {
var data = {
file: downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1),
offset: dataOffset,
chunk: xhrDownload.responseText
};
xhrUpload = new XMLHttpRequest();
xhrUpload.open("POST", uploadUrl, true);
xhrUpload.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhrUpload.send(JSON.stringify(data));
dataOffset += xhrDownload.responseText.length;
};
}
On the PHP side you need something like this:
$in = fopen("php://input", "r");
$postContent = stream_get_contents($in);
fclose($in);
$o = json_decode($postContent);
file_put_contents($o->file . '-' . $o->offset . '.txt', $o->chunk);
These snippets will just give you the basic idea, you'll need to optimize the code yourself.
I am building a javascript component for Firefox that will take in a zip code, and will return the current weather conditions.
The sample code that weather underground uses jQuery, but as I understand it, I cannot include this code in my javascript component, as javascript does not have the functionality to include other javascript files.
At any rate, I have built up my skeleton code. It takes in the zip code and builds up the url
(example: http://api.wunderground.com/api/e17115d7e24a448e/geolookup/conditions/q/22203.json)
I have tried downloading the data from that url, via the following method:
getWeatherByUrl: function(url)
{
var persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",Components.interfaces.nsILocalFile);
file.append("weather-forecaster.dat");
var urlURI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);
persist.saveURI(urlURI,null,null,null,"",file);
return url;
}
This should download the file to the user's profile directory. It indeed does create the file there. However, it does not look like it contains the json data from weather underground.
What exactly is going on? How would I download the file? I believe that there is a query going on when that url is passed to weather underground, but that shouldn't matter as the .json page is what gets spit out from them, right?
Is there a way to do this without downloading the file, but by streaming it and parsing it?
You can simply use XMLHttpRequest to download this data:
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json");
request.addEventListener("load", function(event)
{
var data = JSON.parse(request.responseText);
alert(data.response.version);
}, false);
request.send(null);