網(wǎng)站首頁 編程語言 正文
前言
JS
為什么要用ajax來提交
在使用from提交時(shí),瀏覽器會(huì)向服務(wù)器發(fā)送選中的文件的內(nèi)容而不僅僅是發(fā)送文件名。
為安全起見,即file-upload 元素不允許 HTML 作者或 JavaScript 程序員指定一個(gè)默認(rèn)的文件名。HTML value 屬性被忽略,并且對于此類元素來說,value屬性是只讀的,這意味著只有用戶可以輸入一個(gè)文件名。當(dāng)用戶選擇或編輯一個(gè)文件名時(shí),file-upload 元素觸發(fā) onchange 事件句柄。
利用form提交會(huì)導(dǎo)致頁面刷新,體驗(yàn)不好,所以使用AJAX進(jìn)行文件上傳是個(gè)不錯(cuò)的選擇。但這需要我們自己來組織通過POST請求發(fā)送的內(nèi)容
FormData對象
通過FormData對象可以組裝一組用 XMLHttpRequest發(fā)送請求的鍵/值對。它可以更靈活方便的發(fā)送表單數(shù)據(jù),因?yàn)榭梢元?dú)立于表單使用。如果你把表單的編碼類型設(shè)置為multipart/form-data ,則通過FormData傳輸?shù)臄?shù)據(jù)格式和表單通過submit() 方法傳輸?shù)臄?shù)據(jù)格式相同。 —— MDN web docs
Form的enctype屬性
enctype這個(gè)屬性管理的是表單的MIME編碼,它一共有三個(gè)屬性:
值 | 描述 |
---|---|
application/x-www-form-urlencoded | 在發(fā)送前編碼所有字符(默認(rèn)) |
multipart/form-data | 不對字符編碼,用來制定傳輸數(shù)據(jù)的特殊類型,如mp3、jpg |
text/plain | 純文本傳輸 |
Input
value | 保存了用戶指定的文件的名稱 |
---|---|
type=“file” | 設(shè)置input類型為file |
multiple=“multiple” | 可多選,不設(shè)置為單選 |
accept=“…” | 設(shè)置可選文件的MIME_type。在設(shè)置之后點(diǎn)擊選擇文件按鈕會(huì)默認(rèn)顯示符合設(shè)置的MIME_type的文件(存在兼容性)。具體的文件類型對應(yīng)的MIME類型可以搜索到,這里列出我用到的類型: |
MIME類型(更多直接百度,類型超乎你的想想)
文件類型 | MIME類型 |
---|---|
.txt | text/plain |
application/pdf | |
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xls | application/vnd.ms-excel |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
上傳單個(gè)文件
html代碼部分
<form id="uploadForm" method="post" enctype="multipart/form-data">
<label >上傳電子書</label>
<input type="file" name="file" >
<button id="upload" type="button" name="button" >上傳</button>
</br>
</br>
</br>
</form>
javascript代碼部分
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js "></script>
<script>
$("#upload").click(function(){
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
type: 'post',
url: "{{ url_for('.regression_report') }}", //上傳文件的請求路徑必須是絕對路勁
data: formData,
cache: false,
processData: false,
contentType: false,
success:function(data){
// 這里是訪問成功時(shí)被自動(dòng)執(zhí)行的代碼
// 拆分返回值信息(具體返回什么東西就看視圖函數(shù)中定義的json格式)
status_ret = data.status;
errmsg_ret = data.errmsg;
layer.msg(errmsg_ret);
switch (status_ret){
case 0:
setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");
break
default:
setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");
break
}
},
error:function(jqXHR){
// 這里是訪問失敗時(shí)被自動(dòng)調(diào)用的代碼
}
});
});
</script>
當(dāng)你的頁面樣式比較多的時(shí)候,可能上述方法無法傳入文件,下面這種方法比較強(qiáng),推薦看看
<form class="info" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>File upload</label>
<input id="id_regression_html" type="file" name="regression_html" class="file-upload-default">
<div class="input-group col-xs-12">
<input type="text" class="form-control file-upload-info" disabled="" placeholder="Upload Regression.html">
<span class="input-group-append">
<button id="html_upload" class="file-upload-browse btn btn-gradient-primary" type="button">Html Upload</button>
</span>
</div>
</div>
<button id="id_ajax_submit" type="button" class="btn btn-gradient-primary mr-2">Submit</button>
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js "></script>
<script>
$("#id_ajax_submit").click(function(){
// var formData = new FormData($('#uploadForm')[0]);
let formData = new FormData();
let my_file = document.getElementById('id_regression_html');
// @Param: <input name="regression_html">
// @Param: myFile.file[0]為第一個(gè)文件(單選),多個(gè)文件(多選)則要循環(huán)添加
formData.append('regression_html',my_file.files[0]);
$.ajax({
type: 'post',
url: "{{ url_for('.regression_report') }}", //上傳文件的請求路徑必須是絕對路勁
data: formData,
cache: false,
async: false,
processData: false, //告訴jquery不要處理發(fā)送的數(shù)據(jù)
contentType: false, //告訴jquery不要設(shè)置content-Type請求頭
success:function(data){
// 這里是訪問成功時(shí)被自動(dòng)執(zhí)行的代碼
// 拆分返回值信息(具體返回什么東西就看視圖函數(shù)中定義的json格式)
status_ret = data.status;
errmsg_ret = data.errmsg;
layer.msg(errmsg_ret);
switch (status_ret){
case 0:
setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");
break
case 1:
setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");
break
default:
setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000");
break
}
},
error:function(jqXHR){
// 這里是訪問失敗時(shí)被自動(dòng)調(diào)用的代碼
}
});
});
</script>
flask 視圖函數(shù)部分
@admin_blu.route("/toolReg", methods=['GET', 'POST'])
def regression_report():
if request.method == "GET":
return render_template('index.html')
elif request.method == "POST":
# TODO: 獲取設(shè)置
# TODO: 獲取文件
f = request.files.get('file')
if f and f.filename.__contains__('.html'):
upload_path = os.path.join(current_app.root_path, 'static/upload/html', f.filename) download_path = os.path.join(current_app.root_path, 'static/upload/html', 'xlsx')
# TODO: 類實(shí)例化,同步執(zhí)行
f.save(upload_path)
ret = {
"status": 0,
"errmsg": "上傳成功"
}
return jsonify(ret)
return redirect(url_for(".index.html"))
上傳多個(gè)文件
html
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" multiple="multiple" />
</form>
<button id="btnUpload">上傳文件</button>
js
<script>
$("#btnUpload").on("click", function(){
var formdata = new FormData($("#uploadForm")[0]);
alert(formdata);
$.ajax({
type: "post",
url: "/Attendance/UploadFile2/",//url地址
contentType: false,
cache: false,
processData: false,
data: formdata,
success: function (data) {
console.log(data);
}
});
});
</script>
出問題解決方案
//將formdata改用下面的方式試下
var formdata = new FormData();
var files = $("input[type='file']")[0].files;
for (var i = 0; i < files.length; i++) {
formdata.append("file", files[i]);
}
原文鏈接:https://blog.csdn.net/qq_33704787/article/details/126003341
相關(guān)推薦
- 2022-07-07 redis連接報(bào)錯(cuò)error:NOAUTH?Authentication?required_Redi
- 2022-09-24 Go?GORM?事務(wù)詳細(xì)介紹_Golang
- 2023-01-02 Kotlin類對象class初始化與使用_Android
- 2022-08-26 如何使用pandas對超大csv文件進(jìn)行快速拆分詳解_python
- 2022-04-22 Spring AOP 在注解上使用SPEL表達(dá)式注入對象
- 2022-08-25 Python中如何使用Matplotlib庫繪制圖形_python
- 2022-12-21 Android?O對后臺(tái)Service限制詳解_Android
- 2022-12-22 Python中排序函數(shù)sorted()函數(shù)的使用實(shí)例_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支