溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在JavaScript中使用FormData類上傳文件

發(fā)布時(shí)間:2021-04-16 16:23:17 來(lái)源:億速云 閱讀:273 作者:Leah 欄目:web開(kāi)發(fā)

怎么在JavaScript中使用FormData類上傳文件?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

案例一:xhr.upload.onprogress監(jiān)控文件的上傳進(jìn)度,并且動(dòng)態(tài)顯示

怎么在JavaScript中使用FormData類上傳文件

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
 .progress {
 width: 100px;
 height: 10px;
 background-color: #eee;
 }
 .progress-bar {
 width: 0;
 height: 10px;
 background-color: blue;
 }
 </style>
</head>
<body>
 <form action="" id="form">
 <input type="file" name="file" id="file">
 </form>
 <div class="progress">
 <div class="progress-bar" id="bar"></div>
 </div>
 <script>
 var file = document.getElementById("file");
 var bar = document.getElementById("bar");
 file.onchange = function () {
 var formData = new FormData();
 // 上傳的文件
 formData.append('attrName', this.files[0]);

 var xhr = new XMLHttpRequest();
 xhr.open("post", "/upload");
 // xhr.upload.onprogress監(jiān)聽(tīng)上傳進(jìn)度
 xhr.upload.onprogress = function (ev) {
 // ev.loaded表示上傳了多少,ev.total表示文件的總大小
 var result = (ev.loaded / ev.total * 100).toFixed(2) + '%';
 // result為進(jìn)度百分比
 bar.style.width = result;
 bar.innerHTML = result;
 }
 xhr.send(formData);
 xhr.onload = function () {
 if(xhr.status == 200) {
  console.log(xhr.responseText);
 }
 }
 }
 </script>
</body>
</html>

案例二:服務(wù)器端返回上傳路徑,供客戶端預(yù)覽上傳的圖片效果

成功預(yù)覽我家耶啵的帥照

怎么在JavaScript中使用FormData類上傳文件

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
 .progress {
 display: inline-block;
 width: 600px;
 height: 20px;
 border-radius: 5px;
 background-color: #eee;
 }
 .progress-bar {
 width: 0;
 height: 20px;
 background-color: orange;
 border-radius: 5px;
 font-size: 16px;
 text-align: center;
 color: #fff;
 }
 </style>
</head>
<body>
 <form action="" id="form">
 <input type="file" name="file" id="file">
 <div class="progress">
 <div class="progress-bar" id="bar"></div>
 </div>
 </form>
 
 <div id="box"></div>
 <script>
 var file = document.getElementById("file");
 var bar = document.getElementById("bar");
 var box = document.getElementById("box");
 file.onchange = function () {
 var formData = new FormData();
 // 上傳的文件
 formData.append('attrName', this.files[0]);

 var xhr = new XMLHttpRequest();
 xhr.open("post", "/upload");
 xhr.upload.onprogress = function (ev) {
 // ev.loaded表示上傳了多少,ev.total表示文件的總大小
 var result = (ev.loaded / ev.total * 100).toFixed(2) + '%';
 // result為進(jìn)度百分比
 bar.style.width = result;
 bar.innerHTML = result;
 }
 xhr.send(formData);
 xhr.onload = function () {
 if(xhr.status == 200) {
  var result = JSON.parse(xhr.responseText);
  var img = document.createElement('img');
  img.src = result.path;
  // 圖片加載完成在進(jìn)行顯示,否則用戶會(huì)看到圖片的加載過(guò)程,效果不好
  img.onload = function () {
  box.appendChild(img);
  }
 }
 }
 }
 </script>
</body>
</html>

nodejs服務(wù)器端的部分代碼:

app.post('/upload', (req, res) => {
 // 創(chuàng)建formidable表單解析對(duì)象
 const form = new formidable.IncomingForm();
 // 上傳文件的路徑
 form.uploadDir = path.join(__dirname, 'public', 'uploads');
 // 上傳文件的后綴名保留
 form.keepExtensions = true;
 // 解析客戶端傳遞過(guò)來(lái)的FormData對(duì)象
 form.parse(req, (err, fileds, files) => {
 // 將文件的地址扒出來(lái)以json對(duì)象的形式返回給客戶端
 res.send({
 path: files.attrName.path.split('public')[1]
 });
 })
})

關(guān)于怎么在JavaScript中使用FormData類上傳文件問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI