File API and NodeJs for Picture Upload

Keywords: Javascript html5 JSON Front-end github

File API of HTML5

The file API of HTML5 makes it easier for us to process image uploads.

Example

html code

<div class="form-group">
     <label for="modal_inputFile" class="col-md-3 control-label label-font">Location map:</label>
     <div class="col-md-9">
         <input type="text" readonly="" class="form-control" placeholder="Click on Select File">
         <input type="file" id="modal_inputFile">
         <img src="" class="img-responsive" id="modal-pre" alt="Preview Area" style="max-height: 300px">
     </div>
</div>

Effect:

Here we can get the information of the picture through $("# modal_inputFile")[0].files[0].

Here are the name,size,type attributes we commonly use.

Preview implementation

After choosing a good picture, we all hope to have a preview function. This HTML 5 was also thought of for us.

He provided us with FileReader, a new object.

FileReader This interface is mainly used to read files into memory and read data in files.

So we can do the preview through the date url.

var file = document.getElementById(modal_inputFile'').files[0];
    if (!file) {
    return false;
    }
    var reader = new FileReader();

    reader.readAsDataURL(file);
    reader.onload = function(e) {
    var ib_pre = document.getElementById('modal-pre');
    ib_pre.src = this.result;
}

This realizes the preview.

Let's look at the src of img.

<img src="data:image/png;base64,iVBORXXXXXXXXXXXXX....XXXXXXX" class="img-responsive" id="modal-pre" alt="Preview Area" style="max-height: 300px">

src is base64 encoding.

It can be seen concretely that: HTML5 Authoritative Guide - New Tag Changes, Document API, Drag and Drop API (Brief Learning Notes 1)

Docking with backstage

Since the front-end uses the file API to meet our needs, then we need to upload to the server. NodeJs is the only one who won't let go.

Front end request

The following is an example of a front-end request initiation:

//Picture upload
$('#preUpload').on('click', function(e) {
    var data = new FormData();
    var _files = $("#modal_inputFile")[0].files[0];
    var ect = ($("#modal_inputFile")[0].files[0]).name.split('.')[1];
    if(ect !== 'png'){
        alert('Please upload png picture!')
        return;
    }
    data.append("modal_file", _files);
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: window.stnt_hosts + 'thirdAdmanage/upload/modal',
        data: data,
        contentType: false,
        processData: false
    }).done(function(data, status) {
        console.log('Upload success');
        
    }).fail(function(err) {
        console.log('Upload failure');
    })
})          

Passed here FormData To process the data we need to upload.

Here the data data data is a sequenced object. Just accept it backstage.

Back-end processing

Server side we use node-formidable To deal with image preservation and other operations.

See code:

var formidable = require("formidable");
var form = new formidable.IncomingForm();

//Temporary directory
form.uploadDir = './upload/';


//Preview picture upload
router.post('/upload/modal', function(req, res, next) {
    form.parse(req, function(err, fields, files) {
        if (files.modal_file) {
            rename(files.modal_file.path, files.modal_file.name, 'preview')
            res.send({
                stats:'success',
                data:[]
            })
        }
    })
});

function rename(old, _new, code, bId) {
    var path = './upload/' + code + '/';
        fs.exists(path, function(exists) {
            if (!exists) {
                fs.mkdir(path)
                console.log('Create folders!')
            }
            fs.renameSync(old, path + _new, function(err) {
                if (err) {
                    console.log(err);
                    
                    return;
                }
                console.log('Upload success!')
            })
        })
}

The reason for using fs.renameSync here is that the temporary directory form.uploadDir we set up is data that exists in memory, not real pictures.

Similar to this

We need to save the file to the place we need through fs. This is the picture.

Last

What are the objects of fields and files in form.parse(req, function(err, fields, files) here? You must debug them by yourself. You'll see what it is.

Before I did not know when I opened the browser to search, the results can be imagined to be very tragic, almost all wrong.

So if it's not clear, you have to check github.

And app. use (body Parser. urlencoded ({extended: true}); it is used to parse the data submitted by our usual form form, that is, the request header contains such information as Content-Type: application/x-www-form-urlencoded.

App. use (body Parser. JSON ()) is used to parse json.

Specific articles about body Parser meeting this blogger Research on Body Parser Middleware.

Posted by ulrikqk on Sat, 23 Mar 2019 23:27:28 -0700