不少時候須要利用formdata數據格式進行先後端交互。javascript
前端代碼能夠是以下所示:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上傳文件</title> </head> <body> <form action="uploads1a" id="myform"> <input type="file" name="image" id="file" /> </form> <div id="test"></div> <button id="btn">點擊上傳</button> <div> <img src="" id="see"> </div> <script type="text/javascript"> var btn = document.getElementById("btn"); var file=document.getElementById("file"); var promise=["png","jpg","jpeg","gif","mp3","mp4","svg"]; file.onchange=function(){ var name=file.value; var ext=name.substring(name.lastIndexOf(".") + 1).toLowerCase(); var res=promise.indexOf(ext); if (res<0) { alert("文件格式不正確"); document.getElementById("btn").disabled=true; }else{ document.getElementById("btn").disabled=false; } } btn.onclick = function() { var val=document.getElementById("file").value; if (val.length==0) { return; } var fromData = new FormData(document.forms[0]); fromData.append("test", "formdata"); fromData.append("test1", JSON.stringify({dd:'dd'})); var oAjax = new XMLHttpRequest(); oAjax.open('post', "/formdata", true); //oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //formdata數據請求頭需設置 oAjax.send(fromData); oAjax.onreadystatechange = function() { if (oAjax.readyState == 4) { if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) { console.log(oAjax.responseText); var data=JSON.parse(oAjax.responseText); document.getElementById("see").setAttribute("src",data.imgSrc.replace(/public/,'')); document.getElementById("file").value=""; } else { console.log(oAjax.status); } } }; } </script> </body> </html>
上面代碼不只有直接生成的formdata數據,還有利用append添加的。前端
後端應該怎麼接收?java
接收方案之一是利用nodejs中間件:multiparty,multiparty是nodejs框架express推薦的中間件。node
本文在作接收研究時,採用的是express框架,後端代碼:express
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
var
express = require(
'express'
);
var
router = express.Router();
var
multiparty = require(
"multiparty"
);
router.
get
(
'/'
, function(req, res, next) {
res.render(
'formdata'
);
});
router.post(
'/'
, function(req, res, next) {
console.log(req.body,
"body"
)
//生成multiparty對象,並配置上傳目標路徑
var
form =
new
multiparty.Form({ uploadDir:
'./public/images'
});
form.parse(req, function(err, fields, files) {
console.log(fields, files,
' fields2'
)
if
(err) {
}
else
{
res.json({ imgSrc: files.image[0].path })
}
});
});
module.exports = router;
|
注意在使用中間件時候:json
前端不要執行這句:
oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //formdata數據請求頭需設置
不然multiparty會失效。
後端除了利用這multiparty去接收,還能夠原生去接收。原生接收須要設置
oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //formdata數據請求頭需設置
這時候會出現req.body裏面,而後去解析,不過貌似有些麻煩。本文也沒有處理。
轉:http://www.javashuo.com/article/p-xtawlabw-u.html