File uploads to asp.net web api using pure javascript via ajax - javascript

I am trying to do file uploads through ajax to my web api. My server side codes prove to be working cause I have managed to post files using a debugging Fiddler and it works fine. But I am failing to write successful javascript code that will be able to do the upload.
Below is my html code:
function sendImage() {
var data = new FormData();
var file = document.getElementById('upload').files[0];
data.append("image",file);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp_br=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp_br=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_br.onreadystatechange = function () {
if (xmlhttp_br.readyState == 4 ) {
var data = xmlhttp_br.responseText;
alert(xmlhttp_br.status+" "+data);
var file = JSON.parse(data);
}
}
xmlhttp_br.open("POST","http://localhost:59103/"+"api/upload/testUpload",true);
xmlhttp_br.setRequestHeader("Content-Type","multipart/form-data");
xmlhttp_br.setRequestHeader("filename", file.name);
xmlhttp_br.send(data);
}
<input name="UploadedImage" id="upload" type="file" accept="image/*">
<button onclick="sendImage()"> Upload Image </button>
<img id ="image">
My c# server side code is as follows
public async Task<IHttpActionResult> PostFile()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
Stream img = null;
string filename ="";
foreach (var file in provider.Contents)
{
filename = file.Headers.ContentDisposition.FileName.Trim('\"');
img = await file.ReadAsStreamAsync();
//Do whatever you want with filename and its binaray data.
}
bool status = UploadFileToS3(filename, img, "edu-media");
if (status)
{
return Ok();
}
else
{
return StatusCode(HttpStatusCode.ExpectationFailed);
}
}
Note that I am saving my files to aws s3 buckets and I don't want jQuery, only pure javascript.

Related

Custom Framework using javascript using input parameters of id of content div?

I am creating a mini website that has one HTML snippet file to hold just the content that's desired for each internal link in the navigation bar. Each file shall contain the content that shall be inserted into the content placeholder of the template file (index.html).
I have to create a framework JS file with a "make framework" function that has an input parameter which is id of a content div that will be controlled by the framework.
The "make framework" function shall return an object that has a public method that accepts the name of an HTML snippet file and places the content of the snippet file into the content div.
The "make framework" function shall have a private ajax calling function that accepts callback functions as input parameters.
I do not get how to start my framework or how to do it. I have already created my mini website and each button click shows the content. I know that later on I would have to make it so that those button clicks will be moved inside my navigation bar as links instead of buttons.
index.html
<!DOCTYPE html>
<html>
<head>
<title>JS Framework</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="nav">
<div id="title">
<img src="pics/logo.png" width="160" height="39" alt="">
</div>
<div id="navLink">
Home
avdLayout
JS Framework
Labs
</div>
</div>
<br><br><br><br><br><br><br>
<button onclick="sendRequest('aboutUs.html')">cars</button>
<button onclick="sendRequest('aboutCoffee.html')">people</button>
<div id="bodyContent">
Content Area
</div>
<div id="footer">
Web footer
</div>
<script>
// Make a global XMLHttpRequest Object
var httpReq;
if (window.XMLHttpRequest) {
httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera
} else if (window.ActiveXObject) {
httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+
} else {
alert('ajax not supported');
}
function sendRequest(url) {
httpReq.open("GET", url);
httpReq.onreadystatechange = handleResponse;
httpReq.send(null);
}
function handleResponse() {
if (httpReq.readyState === 4 && httpReq.status === 200) {
var response = httpReq.responseText;
document.getElementById("bodyContent").innerHTML = response;
}
}
sendRequest('aboutUs.html');
</script>
</body>
</html>
AJAX file:
function ajaxCall(url, successFn, errorFn) {
// variable/property that's private to fn ajaxCall
var httpReq;
if (window.XMLHttpRequest) {
httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera
} else if (window.ActiveXObject) {
httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+
} else {
alert('ajax not supported');
}
// private function
function sendRequest() {
//alert ('sending request');
httpReq.open("GET", url);
httpReq.onreadystatechange = handleResponse;
httpReq.send(null);
}
// another private function
function handleResponse() {
//alert('handling response');
if (httpReq.readyState === 4) {
if (httpReq.status === 200) {
var response = httpReq.responseText;
//alert ("response text is " + response);
// wrap the json in parentheses to avoid tripping over javascript ambiguity...
response = "(" + response + ")";
var jsonObj = eval(response);
successFn(jsonObj); // we are passing BACK jsonObj to the HTML page
} else {
errorFn(httpReq); // we are passing BACK the whole httpReq object to the
// HTML page, they can extract error codes etc from there.
}
}
} // handleResponse
sendRequest();
} // ajaxCall
html snippet files:
click here
See the Pen jZKWPo by Sofia (#76342ck) on CodePen.
You can create a function that takes ID of the target object and url of the HTML snippet, then calls the url and appends the response to the target object:
function loadUrl(container,url) {
var httpReq;
var output;
if (window.XMLHttpRequest) {
httpReq = new XMLHttpRequest(); //For Firefox, Safari, Opera
} else if (window.ActiveXObject) {
httpReq = new ActiveXObject("Microsoft.XMLHTTP"); //For IE 5+
} else {
alert('ajax not supported');
}
function sendRequest(url) {
httpReq.open("GET", url);
httpReq.onreadystatechange = handleResponse;
httpReq.send(null);
}
function handleResponse() {
if (httpReq.readyState === 4) {
if (httpReq.status === 200) {
var response = httpReq.responseText;
output = response; // Result of a successful response
} else {
output = httpReq.response; // Result of a failed response
}
document.getElementById(container).innerHTML = output; // Append the response to the designated container
}
}
// Run the script
sendRequest(url);
}
Then you can use this function wherever you need to retrieve a snippet for your index.html, for example:
loadUrl('contentId','aboutUs.html');
You can see a working example here: https://codepen.io/aydin4ik/project/editor/XqBOqr

Read a specific local file [duplicate]

I’m trying to implemennt a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "testing.txt", true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
var allText = rawFile.responseText;
document.getElementById("textSection").innerHTML = allText;
}
}
rawFile.send();
}
What is going wrong here?
This still doesn’t seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101.
I’ve tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?
You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)
function readTextFile(file)
{
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);
}
}
}
rawFile.send(null);
}
And specify file:// in your filename:
readTextFile("file:///C:/your/path/to/file.txt");
After the introduction of fetch api in javascript, reading file contents could not be simpler.
reading a text file
fetch('file.txt')
.then(response => response.text())
.then(text => console.log(text))
// outputs the content of the text file
reading a json file
fetch('file.json')
.then(response => response.json())
.then(jsonResponse => console.log(jsonResponse))
// outputs a javascript object from the parsed json
Update 30/07/2018 (disclaimer):
This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).
Update-2 (disclaimer):
This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.
Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var text = reader.result;
var node = document.getElementById('output');
node.innerText = text;
console.log(reader.result.substring(0, 200));
};
reader.readAsText(input.files[0]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>
...
</div>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
Modern solution:
Use fileOrBlob.text() as follows:
<input type="file" onchange="this.files[0].text().then(t => console.log(t))">
When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.
Here's a more verbose version:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await file.text();
console.log(text);
}
</script>
Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
On older browsers, this should work:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await (new Response(file)).text();
console.log(text);
}
</script>
Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.
Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file">.
Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.
What JS cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.
To allow JS to access to the local fs automatically is needed to create not an html file with JS inside it but an hta document.
An hta file can contain JS or VBS inside it.
But the hta executable will work on windows systems only.
This is standard browser behavior.
Also Google Chrome worked at the fs API, more info here: http://www.html5rocks.com/en/tutorials/file/filesystem/
Using Fetch and async function
const logFileText = async file => {
const response = await fetch(file)
const text = await response.text()
console.log(text)
}
logFileText('file.txt')
Try creating two functions:
function getData(){ //this will read file and send information to other function
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var lines = xmlhttp.responseText; //*here we get all lines from text file*
intoArray(lines); *//here we call function with parameter "lines*"
}
}
xmlhttp.open("GET", "motsim1.txt", true);
xmlhttp.send();
}
function intoArray (lines) {
// splitting all text data into array "\n" is splitting data from each new line
//and saving each new line as each element*
var lineArr = lines.split('\n');
//just to check if it works output lineArr[index] as below
document.write(lineArr[2]);
document.write(lineArr[3]);
}
Provably you already try it, type "false" as follows:
rawFile.open("GET", file, false);
other example - my reader with FileReader class
<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 PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
Source file
</body>
</html>
This might help,
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "sample.txt", true);
xmlhttp.send();
Local AJAX calls in Chrome are not supported due to same-origin-policy.
Error message on chrome is like this:
"Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."
This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.
Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.
Adding to some the above answers, this modified solution worked for me.
<input id="file-upload-input" type="file" class="form-control" accept="*" />
....
let fileInput = document.getElementById('file-upload-input');
let files = fileInput.files;
//Use createObjectURL, this should address any CORS issues.
let filePath = URL.createObjectURL(files[0]);
....
function readTextFile(filePath){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", filePath , true);
rawFile.send(null);
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4){
if(rawFile.status === 200 || rawFile.status == 0){
var allText = rawFile.responseText;
console.log(allText);
}
}
}
}
function readTextFile(file) {
var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
rawFile.open("GET", file, false); // open with method GET the file with the link file , false (synchronous)
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
{
if(rawFile.status === 200) // status 200: "OK"
{
var allText = rawFile.responseText; // Returns the response data as a string
console.log(allText); // display text on the console
}
}
}
rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}
readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path
- read file text from javascript
- Console log text from file using javascript - Google chrome and mozilla firefox in my case i have this structure of files :
the console.log result :
How to read a local file?
By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.
async function loadText(url) {
text = await fetch(url);
//awaits for text.text() prop
//and then sends it to readText()
readText(await text.text());
}
function readText(text){
//here you can continue with your JS normal logic
console.log(text);
}
loadText('test.txt');
If you want to prompt the user to select a file, then read its contents:
// read the contents of a file input
const readInputFile = (inputElement, callback) => {
const reader = new FileReader();
reader.onload = () => {
callback(reader.result)
};
reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
const openFile = (callback) => {
var el = document.createElement('input');
el.setAttribute('type', 'file');
el.style.display = 'none';
document.body.appendChild(el);
el.onchange = () => {readInputFile(el, (data) => {
callback(data)
document.body.removeChild(el);
})}
el.click();
}
Usage:
// prompt the user to select a file and read it
openFile(data => {
console.log(data)
})
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({`enter code here`
url: "TextFile.txt",
dataType: "text",
success: function (data) {
var text = $('#newCheckText').val();
var str = data;
var str_array = str.split('\n');
for (var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
$('#checkboxes').append('<input type="checkbox" class="checkBoxClass" /> ' + str_array[i] + '<br />');
}
}
});
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
});
</script>
</head>
<body>
<div id="checkboxes">
<input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />
</div>
</body>
</html>
Get local file data in js(data.js) load:
function loadMyFile(){
console.log("ut:"+unixTimeSec());
loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
var mA_=mSdata.split("\n");
console.log(mA_.length);
}
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
return f.toString().
replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
return Math.round( (new Date()).getTime()/1000);
}
file of data.js like:
var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});
dynamic unixTime queryString prevents cached.
AJ works in web http://.
This function made for browsers and open file picker dialog and after user selection read file as binary and call callback function with read data:
function pickAndReadFile(callback) {
var el = document.createElement('input');
el.setAttribute('type', 'file');
el.style.display = 'none';
document.body.appendChild(el);
el.onchange = function (){
const reader = new FileReader();
reader.onload = function () {
callback(reader.result);
document.body.removeChild(el);
};
reader.readAsBinaryString(el.files[0]);
}
el.click();
}
And use it like this:
pickAndReadFile(data => {
console.log(data)
})
This is an old question but there two main ideas that we have to be clear. Do we want to read the whole file or get it line by line?
Teo, I want to get the whole file and process it later.
Okay that is very easy we just call text (remember that text assumes that the file is encoded as UTF-8) and handle the file like this:
const $output = document.getElementById('output')
const $file = document.getElementById('file')
const fetchFile = async e => {
const [file] = e.target.files
const text = await file.text()
$output.textContent = text
}
$file.onchange = fetchFile
<input id='file' type='file' accept='text/plain'><br>
<pre id='output'>...</pre>
What about line by line? It is possible?.
Well my young Padawan, that is also possible we just need a split the text in lines like this
const $output = document.getElementById('output')
const $file = document.getElementById('file')
let count
const fetchFile = async e => {
const [file] = e.target.files
if (!file) return
count = 0
const text = await file.text()
$output.textContent = text
const lines = text.split(/\r?\n/gm)
for (const line of lines) {
if (line) count++
}
console.log({count})
}
$file.onchange = fetchFile
<input id='file' type='file' accept='text/plain'><br>
<pre id='output'>...</pre>
You can import my library:
<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js?pe=yikuansun2015#gmail.com"></script>
then, the function fetchfile(path) will return the uploaded file
<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js"></script>
<script>console.log(fetchfile("file.txt"))</script>
Please note: on Google Chrome if the HTML code is local, errors will appear, but saving the HTML code and the files online then running the online HTML file works.
In order to read a local file text through JavaScript using chrome, the chrome browser should run with the argument --allow-file-access-from-files to allow JavaScript to access local file, then you can read it using XmlHttpRequest like the following:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var allText = xmlhttp.responseText;
}
};
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
I know, I am late at this party. Let me show you what I have got.
This is a simple reading of text file
var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
I hope this helps.

'Cross Origin' error message resulting from local XmlHttpRequest

I am using AJAX to display upcoming events on a website. To that end, I call a JavaScript function via onload="showEvents(3);", see the function below:
function showEvents (amount) {
// are there Events?
if (document.getElementById("eventsDiv")) {
document.getElementsByClassName("info")[0].innerHTML = 'Loading events...';
// initialize XML Http Request
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("eventsDiv").innerHTML = xmlhttp.responseText;
}
}
// send request
xmlhttp.open("GET", "./events.php?number=" + encodeURIComponent(amount), true);
xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.send();
}
}
The file events.php is a PHP file in the same directory, and it connects to the database to fetch the upcoming events. The HTML header of the main website includes
<base href="http://www.my-domain.com/">
The problem: I get a "Cross Orign" error message (in Firefox), preventing my parent index.html file accessing the events.php. As I understand, this error message should not appear since I am using a resource from the same directory.
Ok that's ok, you also can do like this...
if($_SERVER['HTTP_ORIGIN'] == "http://your-domain.com") {
header('Access-Control-Allow-Origin: http://your-domain.com');

C# aspx image upload using angular

I am using aspx page with angular js.
I've used angular and c# webmethod file upload.
I've tried to upload the image like used in web api.
When using web api, the image is uploaded successfully. When I try
with aspx, the webmethod is not hitting, but the result is coming with
the status success and also with the html page.
'
C# server side code didn't hit anyway.
The following is my Angular code which is working with Web api
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
var form = new FormData();
if (file)
form.append("image", file);
var url = "Page.aspx/UploadImage";
xhr.open("Post", url, true);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function () {
reject(xhr.statusText);
};
xhr.send(form);
});
C#:
public static string UploadImage()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
httpPostedFile = HttpContext.Current.Request.Files["image"];
if (Path.GetExtension(httpPostedFile.FileName) == "" || !allowedImageTypes.Contains(Path.GetExtension(httpPostedFile.FileName), StringComparer.CurrentCultureIgnoreCase))
BLErrorHandler.ApplicationError("Invalid image type", ValidationError.ERR28);
}
}

letting user open an xml file on client and parse it using javascript

I'm trying to let a users on my site to save and XML file one the local machine and then later to load them using the HTML file element.
Saving the file what done with iFrame.
When trying to let the user load the file i am getting exceptions all the time.
I've tried every thing i could find over the web and can't seem to find the way to do it.
I am getting all kind of exception, like cross domain or XMLHttpRequest cannot load file:///C:/fakepath/Regions.xml. Cross origin requests are only supported for HTTP.
Depending on the code i tried.
I read that HTML5 standard replace the url with "fakepath", and can't find solution for this. Is there no way to let the user load a file from his own computer to be edited? loading a specific file from server is not a problem but i want to give this freedom to the user and not decide for them what file to load, and also to let them save and load the xml on their computer and not the server
Is there a solution for this problem?
Found this codes but neither helped (and I've tried few other veriations of this):
1)
var error = "";
strFile = document.frmLoadFile.selectedFile.value;
intPos = strFile.lastIndexOf("\\");
strDirectory = strFile.substring(0, intPos);
//alert(strDirectory);
document.frmLoadFile.selectedFile.value = strDirectory;
var file = 'file:\\\\\\' + document.frmLoadFile.selectedFile.value;
try //Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(file);
}
catch (e) {
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load(file);
}
catch (e) {
try //Google Chrome
{
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", file, false);
xmlhttp.send(null);
xmlDoc = xmlhttp.responseXML.documentElement;
}
catch (e) {
error = e.message;
}
}
}
2)
var xmlDoc;
var xmlloaded = false;
function xml_initLibrary(file) {
importXML(file);
}
function importXML(xmlfile) {
try {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception) {
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while (xmlDoc.readyState != 4) { };
xmlDoc.load(xmlfile);
xmlloaded = true;
readXML();
}
else {
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = readXML;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded) {
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
xmlloaded = true;
readXML();
}
}
function readXML() {
//console.log(xmlDoc);
}
does any one knows if there is a way to fix this? of do you need to save the files on the server?
Thank you all very much
Erez
I think you're looking for FileReader, new in HTML5. For IE < 10 you'll need to use the ActiveX FileSystemObject.
This code works for me on Chrome.
<script type="text/javascript">
function doit(e) {
var files = e.target.files;
var reader = new FileReader();
reader.onload = function() {
var parsed = new DOMParser().parseFromString(this.result, "text/xml");
console.log(parsed);
};
reader.readAsText(files[0]);
}
document.getElementById("selectfile").addEventListener("change", doit, false);​
</script>
<input type="file" id="selectfile" />
http://jsfiddle.net/xKuPV/

Categories

Resources