如何将文件发送到Restify API并将其保存在MySQL中

时间:2017-03-06 18:15:47

标签: javascript jquery mysql node.js restify

对于学校项目,我需要通过拖放操作将文件上传到mariadb表。 我目前正在使用node.js并为后端进行解析,并为前端使用jquery。我无法设法让它发挥作用 以下是我发送文件的方式:

<div id="drop">Drop the file</div> <div id="status1"></div> <button id="send" >send</button>

$(function () {

var dropzone = $("#drop");
var sendFile;

$("#send").click(function () {
    $.ajax({
        url: "172.16.3.146:8000/subir",
        type: 'POST',
        data :{file:sendFile},
        cache:false,
        contentType:false,
        processData:false,
        success: function(data,error){
            alert(data+" "+error);
        },
        error: function(data,error){
            alert("something happened "+data+" "+error);
        }
    });
});

 dropzone.on('drop', function (e) {
    console.log("droped");
    $(this).css('border', '2px dotted #0B85A1');
    e.preventDefault();
    var files = e.originalEvent.dataTransfer.files;

    handleFileUpload(files);

});

function handleFileUpload(files) {   
    sendFile = new FormData();        
    sendFile.append('file', files[0]); 
    $('#status1').html("file--->" + files[0].name + " --> " + files[0].size + " KB");                
     
    console.log("uploaded " + files[0].name + files[0].size);
}

对于后端,我已经看到restify不支持多部分表单数据并阅读一些需要的库但是真的不理解这个概念并设法让它工作。 这是我的应用程序:

var restify = require('restify');
var request = require('request');
var mysql = require('mysql');

connection = mysql.createConnection({
    host: 'localhost',
    user: 'servilleta',
    password: 'guest',
    database: 'guest'
});

var ip_addr = '172.16.3.146';
var port = '8000';
var http = require('http');
var server = restify.createServer({
    name: 'apirest'
});

server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.listen(port, ip_addr, function () {
    console.log('%s active on %s ', server.name, server.url);
});

function uploadFile(req, res, next) {
console.log("A file wants to be uploaded");
var query = "LOAD DATA LOCAL INFILE '" + req.params.file + "'INTO TABLE Practica11 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\r\n' (nombre,ApellidoPat,ApellidoMat,NumeroCuenta,Carrera) ";
connection.query(query, function (error, result) {
    if (error) throw error;
    res.send(200, result);
    return next();
    });
}
request.post({
    path: '/subir/',
    formData: formData
}, uploadFile);

connection.end();

很抱歉这篇长篇文章。

0 个答案:

没有答案