有時(shí)候我們不想使用form表單上傳文件,而是想使用ajax茴晋,這里我們提倡用formdata的形式
但是也會(huì)遇到很多坑
首先說前臺(tái)
<body>
<input type="file" id="files">
<button id="btn">上傳</button>
</body>
內(nèi)容部分就是這些陪捷,因?yàn)槭怯脕頊y試的
$("#btn").click(function () {
var pic=$("#files")[0].files[0];
var formdata=new FormData();
console.log(pic);
formdata.append("thumbnail",pic);
console.log(formdata);
$.ajax({
url:"/upload",
type:"POST",
data:formdata,
processData:false,
contentType:false,
success:function (data) {
console.log("返回的數(shù)據(jù): " + data );
}
})
});
這里有幾個(gè)注意點(diǎn)
第一、如何獲取type=file的值
var pic=$("#files")[0].files[0];
第二诺擅、ajax必須寫上contentType:false,和processData:false
contentType為什么要設(shè)置為false揩局,請看https://blog.csdn.net/death05/article/details/80065742
processData為什么為false
processData:
要求為Boolean類型的參數(shù),默認(rèn)為true掀虎。默認(rèn)情況下凌盯,發(fā)送的數(shù)據(jù)將被轉(zhuǎn)換為對象(從技術(shù)角度來講并非字符串)以配合默認(rèn)內(nèi)容類型"application/x-www-form-urlencoded"。如果要發(fā)送DOM樹信息或者其他不希望轉(zhuǎn)換的信息烹玉,請?jiān)O(shè)置為false驰怎。
現(xiàn)在來說說后臺(tái)
var express = require('express');
var router = express.Router();
var fs = require('fs');
var path= require("path");
var formidable = require('formidable');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post("/upload",function (req,res,next) {
console.log('開始文件上傳....');
var form = new formidable.IncomingForm();
//設(shè)置編輯
form.encoding = 'utf-8';
//設(shè)置文件存儲(chǔ)路徑
form.uploadDir = "./public/images/";
//保留后綴
form.keepExtensions = true;
//設(shè)置單文件大小限制
form.maxFieldsSize = 2 * 1024 * 1024;
form.parse(req, function(err, fields, files) {
console.log(files);
console.log(files.thumbnail.path);
console.log('文件名:'+files.thumbnail.name);
var t = (new Date()).getTime();
//生成隨機(jī)數(shù)
var ran = parseInt(Math.random() * 8999 +10000);
//拿到擴(kuò)展名
var extname = path.extname(files.thumbnail.name);
//path.normalize('./path//upload/data/../file/./123.jpg'); 規(guī)范格式文件名
var oldpath = path.normalize(files.thumbnail.path);
//新的路徑
let newfilename=t+ran+extname;
var newpath = './public/images/'+newfilename;
console.warn('oldpath:'+oldpath+' newpath:'+newpath);
fs.rename(oldpath,newpath,function(err){
if(err){
console.error("改名失敗"+err);
}
res.render('index', { title: '文件上傳成功:', imginfo: newfilename });
});
//res.end(util.inspect({fields: fields, files: files}));
});
});
module.exports = router;