我想将表单数据保存到数据库中,并将相同的表单文件上传到dropbox。
我可以使用强大的内容将文件分别上传到dropbox,我无法将两者合并。
提前致谢!!
HTML表格:
<form id="content" enctype="multipart/form-data" method="post">
<fieldset>
<legend>New Content</legend>
title : <input type="text" name="tit" id="tit"/><br><br>
category : <input type="text" name="cat" id="cat"/><br><br>
description : <input type="text" name="des" id="des"/><br><br>
file : <input type="file" name="file" id="file"/><br><br>
<input type="submit" value="Submit" name="submit"><br><br>
<div class="resu"></div>
</fieldset>
</form>
Ajax请求:
$(document).ready(function() {
$('#content').submit(function(event) {
var title = $('input[name=tit]').val();
var category = $('input[name=cat]').val();
var desc = $('input[name=des]').val();
var file = $('input[name=file]').val();
var filename = file.split("\\").pop();
$.ajax({
type : 'POST',
url : 'http://127.0.0.1:8081/addContent',
data : {"user_id": 12, "title": title, "description": desc, "category": category, "file_name": filename},
dataType : 'application/json',
encode : true,
})
.done(function(data) {
//$(.result).html(data);
console.log(data);
});
event.preventDefault();
});
});
Node.Js文件
router.post("/", function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
//console.log(files);
// `file` is the name of the <input> field of type `file`
var temp_path = files.file.path,
file_type = files.file.type,
file_name = files.file.name;
//new_path = 'uploads/';
node_dropbox.Authenticate(app_key, app_secret, 'redirect_url', function(err, url){
//console.log(url);
});
node_dropbox.AccessToken(app_key, app_secret, 'access_code', 'redirect_url', function(err, body) {
var access_token = body.access_token;
var token = token;
var api = node_dropbox.api(token);
fs.readFile(temp_path, function(err,content){
if(!err){
request.put('https://api-content.dropbox.com/1/files_put/auto/files/upload/' + file_name, {
headers: {Authorization: 'Bearer ' + token, 'Content-Type': file_type},
body: content},
function optionalCallback(err, httpResponse) {
if (err) {
console.log('Not Uploaded');
res.end();
}
else {
console.log("Uploaded Successfully");
var query="INSERT INTO kind_heart.contents(user_id, title, category, description, content_status, date_time, file_name) VALUES(?,?,?,?,'Uploaded',NOW(),?)";
var datafromjson = [req.body.user_id, req.body.title, req.body.category, req.body.description, req.body.file_name];
console.log("SQL Query: " + query);
connection.query(query, datafromjson, function(err, rows, fields) {
if(err){
console.log(err);
console.log("Error: Not Uploaded");
res.end("Error: Not Uploaded");
}else{
//res.writeHead(200, {'Content-Type': 'application/json'});
var result = JSON.stringify(rows);
res.end(result);
console.log("Uploaded Succesfully!!");
}
});
res.end();
}
});
}
});
});
});
});