js上傳檔案
- IT科技
- 關注:1.21W次
js上傳檔案是怎樣的呢?下面就讓我們一起來了解一下吧:
在js中實現上傳檔案功能一般是可以運用input完成上傳,在上傳時需要選擇檔案,選擇檔案之後,提交後就會出現圖片url,當然需要注意的是,其傳輸格式大部分是採用form-data形式上傳的。
參考範例:
在js中實現上傳檔案可使用的程式碼,html部分的程式碼為:
<form id="upload" enctype="multipart/form-data" method="post">
<input type="file" name="file" id="pic"/>
<input type="button" value="提交" onclick="uploadPic();"/>
<span class="showUrl"></span>
<img src="" class="showPic" alt="">
</form>
js部分的程式碼為:
function uploadPic() {
var form = document.getElementById('upload'),
formData = new FormData(form);
$.ajax({
url:"https://sscpre.boe.com/v1/medical-console/medical/file/upload",
type:"post",
data:formData,
processData:false,
contentType:false,
success:function(res){
if(res){
alert("上傳成功!");
}
console.log(res);
$("#pic").val("");
$(".showUrl").html(res);
$(".showPic").attr("src",res);
},
error:function(err){
alert("網路連線失敗,稍後重試",err);
}
})
}
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/mpw9zn.html