0

Im trying to build file preview feature before file being uploaded to the server.

Im stucked with the problem of reading file from the user's computer, not a server

Im usuing jquery Fileupload which fires the file processing on the change function

  return $('#new_order_file').fileupload({
    change: function(e, data) {
        return $.each(data.files, function(index, file) {
            read_file(file);
            console.log(file)
        });
    },
  });

Log gives File - name, size, type, proto and LastmodifiedDate

Than, this part is tricky for me, I know that I have to use FileReader() but Im not sure how to

function read_file(f){
    var reader = new FileReader();
    reader.onload = function(e) {
        $('#CO-show-model').css('display', 'block');
        loaded(f.name, e.target.result);
    };
    reader.readAsArrayBuffer(f);
}

Next, loaded function is for displaying the file model using three.js

function loaded(file) {
    var uploaded_file = file // gives 404
    // var uploaded_file = './stl/test-file.stl' // ASCII test
}

The fucntion itself is good, I tested it with an hardcoded path to some test file. But the problem is that it was on a server. Now, script gives an 404 for http://example.com/filename.stl which is true, because I pass file.name there. If I just pass file, it gives 404 for http://example.com/[object%20File]

Edit 1: I tried suggest ReadAsDataUrl, but seems to be that it's not supported by three.js. Also, the FileReader() seems to be ok

Sergey Khmelevskoy
  • 2,429
  • 3
  • 19
  • 43
  • 1
    Possible duplicate of [get the data of uploaded file in javascript](http://stackoverflow.com/questions/16505333/get-the-data-of-uploaded-file-in-javascript) – CollinD Jul 26 '16 at 21:44

2 Answers2

1

Your file is an object so you have to get the right attribute from it. Take a look here Filereader Mozilla documentation

Nirmi
  • 1,099
  • 1
  • 8
  • 20
1

It's a security feature. Browsers will not give you the actual local url to the file you are uploading.

See How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

Edit: Maybe what you are looking for is this question instead? What is the preferred method for loading STL files in Three.js

Community
  • 1
  • 1
Dogoku
  • 4,585
  • 3
  • 24
  • 34
  • That explain a lot. However, some website have this feature. I was actually trying to adopt source code from http://www.viewstl.com and their FileReader seems to be ok :( – Sergey Khmelevskoy Jul 30 '16 at 16:19
  • I think your question is wrong then. Are you asking how to read the data of a file in Javascript or how to get the full path to a file? viewstl.com are simply showing the filename, which you do have access to. – Dogoku Jul 30 '16 at 16:25