ajax upload files and nodeJS reception

ajax file upload need to use FormData

The official introduction

FormData compiled into the object data for key-value pairs to use XMLHttpRequestto transmit data. The main form for transmitting data, but can be used for transmitting data keyed (keyed data), and used in independent form. If the form enctypeattribute set to multipart / form-Data  , the form will be used submit()for data transmission method, whereby the transmission data have the same form.

Links: https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

Write your own simple example:

html part:

<body>
    <form action="/" enctype="multipart/form-data" id="form">
        姓名:<input type="text" name="username" id=""><br>
        年龄:<input type="text" name="age" id=""><br>
        <br>
        本人照片:<input type="file" name="img" id="" value="选择照片"><br><br>
        <input type="button" value="确认提交" name="btn" id="btn">
    </form>
</body>
<script src="./jquery.js"></script>
<script>
    $('#btn').the Click ( new new=inpDatavaruse formData entire form data package//() {
        function
          FormData(document.getElementById('form'));      
        $.ajax({
            url:'http://soul:7777/file',
            type:'post',
            contentType: false,
            Data: inpData, // labeled data packets can be sent directly via Send 
            the processData: to false ,
            success:function(data){
                if(data){
                    Alert ( ' success ' )
                }else{
                    Alert ( ' failure ' )
                }
            }
        })
    })

</script>

js file server need to use the formidable receiving module to help us deal with documents and other data;

js part of the code:

var http = require('http');
var fs = require('fs');
var server = http.createServer();
server.listen('7777', function () {
    console.log ( 'Welcome to the world's 6' );
});
server.on('request', function (req, res) {
    res.setHeader ( 'Access-Control-the Allow-Origin', '*' );
     IF (req.url == '/ File' ) {
         var FD = the require ( 'C: / the Users / Administrator / AppData / Roaming / NPM / node_modules / formidable ' );
         var form = new new fd.IncomingForm ();
         // If the file is moved across the letter still need to upload files path in advance, by default c drive 
        form.uploadDir =' E: / img ' ;
        form.parse (REQ, function (ERR, Fields, Files) {
             // the console.log (filds); // form data 
            // data // uploaded file; the console.log (Files) 
            // the need to upload file to the specified directory 
            fs.rename (files.img.path, './img/' + files.img.name, function (ERR) {
                 // Get json data parsing 
                fs.readFile ( './ db.json ',' UTF8 ', function (ERR, json_str) {
                     var json_arr = the JSON.parse (json_str);
                     // assembling new data 
                    // id id obtain the last element in the array + 1 is the id value of a new array of 
                    fields. id = json_arr [json_arr.length - 1] .id + 1;
                
                    // the address of the picture has moved a good new data is added to the inside 
                    fields.img = '/ IMG /' + files.img.name;
                     // new data is added to the array 
                    json_arr.push (fields);

                    // array back to a string write josn file 
                    fs.writeFile ( './ db.json', JSON.stringify (json_arr), function (ERR) {
                         IF (! ERR) {
                             // return message 
                            res. End ( '. 1' );
                        } else {
                            res.end('0');
                        }
                    });
                });
            });
        });
    }
});

 

Multi-file upload need to input: file labels add attributes multiple="multiple"(see online)

Summary about:

The key is used to upload files ajax formdata object, the server key is formidable technical data processing module, and then json file additions and deletions.

Guess you like

Origin www.cnblogs.com/ruoruchujian/p/11028284.html