I want to get a file object in TypeScript from a html file-Input-Type.? - input

public UploadFile()
{
//File Data
this.filePath = $("#inputFile").val();
var file = $("#inputFile").get(0).files[0];
var reader = new FileReader();
reader.onload = function (evt) {
var fileContent = reader.result;
var x = fileContent.bytes;
}

Your question isn't completely clear, but here's some sample code that may help. This should be valid TypeScript code, which reads a file from input element #inputFile and displays the text from it in a div with id #divMain.
$("#inputFile").on('change', null, (e) => {
var input = <HTMLInputElement>e.target;
var files = input.files;
var f:File = files[0];
var reader = new FileReader();
var name = f.name;
console.log("File name: " + name);
reader.onload = function (e) {
var target: any = e.target;
var data = target.result;
$("#divMain").text(data);
};
reader.readAsText(f);
});

Related

How to pass pdf file to Controller that requires IFormFile

I've been working on this the whole day and did my research already, I can't seem to find a solution anywhere. I have this function that calls a List in my controller, the List needs a IFormFile parameter,
here's my javascript method
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
data: { CFile: r}, // I'm trying to pass the pdf file here
cache: false,
success: function (data) {
console.log(data);
}
});
}
and this is my List in controller
public object _Index(IFormFile CFile)
{
if (CFile != null)
{
try
{
string documentText = "";
using PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
documentProcessor.LoadDocument(CFile.OpenReadStream());
documentText = documentProcessor.Text;
string word = #"([0-9]+.[0-9]+-[0-9]+)";
Regex regex = new Regex(word);
foreach (Match match in regex.Matches(documentText))
{
sectionsList.Add(match.Value.ToString());
}
}
catch
{
Response.StatusCode = 400;
}
}
else
{
_logger.LogInformation("empty");
}
return sectionsList;
}
the CFile is always empty i tried different ways already like passing
data: { CFile: e.file}
Does anyone else have idea?
From this code data: { CFile: e.file}, you post it as the string, so it can not be recognized as a file. You need to use FormData and change the contentType.
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
//----------edit here---------
var form = new FormData()
form.append('CFile', file)
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
method:'post',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
}
});
}
The bakend should add [FromForm].
[HttpPost]
public object _Index([FromForm]IFormFile CFile)

image in image (overlay image) with gm (GraphicsMagick)

I want to put a watermark picture (logo) on my resized pictures as you can see in the code below.
Can somebody help how to put a picture in the right low corner with a opacity of 50%?
var fs = require('fs')
, gm = require('gm');
function walk(currentDirPath, callback) {
var fs = require('fs'), path = require('path');
fs.readdirSync(currentDirPath).forEach(function(name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walk(filePath, callback);
}
});
}
var inputDir = "/Users/USER/Desktop/src/"
var outputDir = "/Users/USER/Desktop/target/"
walk(inputDir, function(filePath, stat) {
// match filename like IMG_1234.JPG
var filename = filePath.match(/IMG_\d{4}.JPG/gmi).toString();
console.log(filename);
var outputfile = outputDir + filename
var readStream = fs.createReadStream(filePath);
gm(readStream, filename)
.size({bufferStream: true}, function(err, size) {
this.resize(size.width / 2, size.height / 2)
this.write(outputfile, function (err) {
if (!err) console.log('done');
});
});
});
Here is the solution:
.draw(['image Over 0,0 0,0 /Users/USER/Desktop/target/nike-global-diversity-logo.png'])
put this line of code after gm call and before the resizing.

WebRTC Play Audio Input as Microphone

I want to play my audio file as microphone input (without sending my live voice but my audio file) to the WebRTC connected user. Can anybody tell me how could it be done?
I have done some following tries in the JS code, like:
1. base64 Audio
<script>
var base64string = "T2dnUwACAAAAAAA..";
var snd = new Audio("data:audio/wav;base64," + base64string);
snd.play();
var Sound = (function () {
var df = document.createDocumentFragment();
return function Sound(src) {
var snd = new Audio(src);
df.appendChild(snd);
snd.addEventListener('ended', function () {df.removeChild(snd);});
snd.play();
return snd;
}
}());
var snd = Sound("data:audio/wav;base64," + base64string);
</script>
2. AudioBuffer
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var isPlaying = false;
var sourceNode = null;
var theBuffer = null;
window.onload = function() {
var request = new XMLHttpRequest();
request.open("GET", "sounds/DEMO_positive_resp.wav", true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData( request.response, function(buffer) {
theBuffer = buffer;
} );
}
request.send();
}
function togglePlayback() {
var now = audioContext.currentTime;
if (isPlaying) {
//stop playing and return
sourceNode.stop( now );
sourceNode = null;
analyser = null;
isPlaying = false;
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
//window.cancelAnimationFrame( rafID );
return "start";
}
sourceNode = audioContext.createBufferSource();
sourceNode.buffer = theBuffer;
sourceNode.loop = true;
analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
sourceNode.connect( analyser );
analyser.connect( audioContext.destination );
sourceNode.start( now );
isPlaying = true;
isLiveInput = true;
return "stop";
}
Please help me out in this case. It would be highly appreciable.
Here is a demo that may help you stream mp3 or wav using chrome:
https://www.webrtc-experiment.com/RTCMultiConnection/stream-mp3-live.html
Here is, how it is written:
http://www.rtcmulticonnection.org/docs/getting-started/#stream-mp3-live
And source code of the demo:
https://github.com/muaz-khan/RTCMultiConnection/blob/master/demos/stream-mp3-live.html
https://github.com/muaz-khan/WebRTC-Experiment/issues/222
Use in 3rd party WebRTC applications
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var gainNode = context.createGain();
gainNode.connect(context.destination);
// don't play for self
gainNode.gain.value = 0;
document.querySelector('input[type=file]').onchange = function() {
this.disabled = true;
var reader = new FileReader();
reader.onload = (function(e) {
// Import callback function that provides PCM audio data decoded as an audio buffer
context.decodeAudioData(e.target.result, function(buffer) {
// Create the sound source
var soundSource = context.createBufferSource();
soundSource.buffer = buffer;
soundSource.start(0, 0 / 1000);
soundSource.connect(gainNode);
var destination = context.createMediaStreamDestination();
soundSource.connect(destination);
createPeerConnection(destination.stream);
});
});
reader.readAsArrayBuffer(this.files[0]);
};
function createPeerConnection(mp3Stream) {
// you need to place 3rd party WebRTC code here
}
Updated at: 5:55 PM - Thursday, August 28, 2014
Here is how to get mp3 from server:
function HTTP_GET(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200) {
alert("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(xhr.response); // return array-buffer
};
}
// invoke above "HTTP_GET" method
// to load mp3 as array-buffer
HTTP_GET('http://domain.com/file.mp3', function(array_buffer) {
// Import callback function that provides PCM audio data decoded as an audio buffer
context.decodeAudioData(array_buffer, function(buffer) {
// Create the sound source
var soundSource = context.createBufferSource();
soundSource.buffer = buffer;
soundSource.start(0, 0 / 1000);
soundSource.connect(gainNode);
var destination = context.createMediaStreamDestination();
soundSource.connect(destination);
createPeerConnection(destination.stream);
});
});

How can I save a zip file to local storage in a win8 app using JSZip?

I'm able to create the JSZip object in my code, but I'm having trouble saving that to local storage in my windows 8 app. The examples I'm able to find set the browser's location.href to trigger a download, which isn't really an option for me.
I've included my code below. The zip file I end up with is invalid and can't be opened. Any help would be appreciated.
For reference: JSZip
function _zipTest() {
var dbFile = null;
var zipData = null;
Windows.Storage.StorageFile.getFileFromPathAsync(config.db.path)
.then(function (file) {
dbFile = file;
return Windows.Storage.FileIO.readBufferAsync(file);
})
.then(function (buffer) {
//Read the database file into a byte array and create a new zip file
zipData = new Uint8Array(buffer.length);
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
dataReader.readBytes(zipData);
dataReader.close();
var localFolder = Windows.Storage.ApplicationData.current.localFolder;
return localFolder.createFileAsync(dbFile.displayName.concat('.zip'), Windows.Storage.CreationCollisionOption.replaceExisting)
})
.then(function (file) {
//Write the zip data to the new zip file
var zip = new JSZip();
zip.file(dbFile.displayName, zipData);
var content = zip.generate();
return Windows.Storage.FileIO.writeTextAsync(file, content);
});
}
you can do something on these lines. This code seem to generate valid .zip file in the temp folder.
var zip = new JSZip();
var storage = Windows.Storage;
storage.StorageFile.getFileFromApplicationUriAsync(new Windows.Foundation.Uri('ms-appx:///images/logo.png')).then(function ongetfile(file)
{
var blob = MSApp.createFileFromStorageFile(file);
var url = URL.createObjectURL(blob, { oneTimeOnly: true });
return WinJS.xhr({ url: url, responseType: 'arraybuffer' });
}).then(function onreadbuffer(req)
{
var b = req.response;
zip.file('logo.png', b);
return storage.ApplicationData.current.temporaryFolder.createFileAsync('a.zip', storage.CreationCollisionOption.replaceExisting);
}).then(function onnewfile(out)
{
var content = zip.generate({ type: 'uint8array' });
return storage.FileIO.writeBytesAsync(out, content);
}).then(null, function onerror(error)
{
// TODO: error handling
});

google maps api v2 map.removeOverlay() marker array issue

To start off with, I would like to say that I have been looking on the internet for a really long time and have been unable to find the answer, hence my question here.
My latest school project is to create an admin page for adding articles to a database, the articles are connected to a point on a google map. The requirement for adding the point on the map is that the user is able to click the map once and the marker is produced, if the map is clicked a second time the first marker is moved to the second location. (this is what I am struggling with.)
The problem is, as the code is now, I get the error that markersArray is undefined. If I place the var markersArray = new Array; underneath the eventListener then I get an error that there is something wrong the main.js (googles file) and markersArray[0] is undefined in the second if.
By the way, I have to use google maps API v2, even though it is old.
<script type="text/javascript">
//<![CDATA[
var map;
var markers = new Array;
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
if (this.counter == 0) {
if (latlng) {
var marker = new GMarker(latlng);
latlng1 = latlng;
this.map.addOverlay(marker);
this.counter++;
markers.push(marker); //This is where I get the error that markersArray is undefined.
}
}
else if (this.counter == 1) {
if (latlng){
alert (markers[0]);
this.map.removeOverlay(markers[0]);
var markers = [];
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}
I solved the problem. I'm not exactly sure why it worked but this is what it looks like now:
var markersArray = [];
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var type = Articles[i].getAttribute("type");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
var marker = new GMarker(latlng);
if (this.counter == 0) {
if (latlng) {
latlng1 = latlng;
this.map.addOverlay(marker);
markersArray.push(marker);
this.counter++;
}
}
else if (this.counter == 1) {
if (latlng){
this.map.removeOverlay(markersArray[0]);
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}