简体   繁体   中英

preprocess angular2 upload file

I am building an import tool in angular2. The process is to allow the user to provide a csv file and then fill in how they want the data mapped to the system. So the steps would be 1. Select a local file (using file upload) 2. Instead of sending the file to the server it will be loaded into an array inside angular2 and then displayed on the screen.

Are there any examples of this.

You'll have a lot of trouble accessing a file in the local file system using JavaScript, mainly because browsers won't let you do that for security reasons (imagine the viruses). Your JavaScript code runs on an isolated sandbox so by design there's no way to do this (check https://stackoverflow.com/a/33803293/165606 for references on the topic).

The only way you can load local text files is by renaming them into ".js" files (manually), adding them to your project folder and includying them in your HTML header, or using some kind of middleware like Cordova (if you're making a mobile app), or doing some advanced browser-specific configurations to deactivate the file system security rules (not trivial to do for a non-technical user, on purpose).

In case you may decide to work with uploaded files, here's some libraries and demos to upload and open CSV files with Angular 2.

File upload:

https://github.com/valor-software/ng2-file-upload

Demo: http://valor-software.com/ng2-file-upload/

Read CSV:

http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html#.WV1-cXXyuHs

Demo: http://demo.sodhanalibrary.com/angular2/readCsvData.html

So I was able to prove I could get this to work by using this fiddle that someone posted. http://jsfiddle.net/thzytf1w/2/

var fileInput = document.getElementById("csv"),

readFile = function () {
    var reader = new FileReader();
    reader.onload = function () {
        document.getElementById('out').innerHTML = reader.result;
    };
    // start reading the file. When it is done, calls the onload event defined above.
    reader.readAsBinaryString(fileInput.files[0]);
};

fileInput.addEventListener('change', readFile);

I'm in the process of getting it to work with angular2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM