问题来源
事情是这样的,在一个表单中有文件,也有其他文本等参数,后台让我用formData格式传输。疯狂百度后,有如下总结
具体解决方案
首先,除了formdata之外,要解决文件上传的问题。
1. 文件上传代码
1.form标签写法:
<form class="form-horizontal" style="margin-top: 20px;" id="inputer" enctype="multipart/form-data">
2.input标签写法
<input type="file" id="fileExport" class='real-upload-btn' accept=".pdf">
注意点:
(1)form中加enctype=“multip加粗样式art/form-data”
(2)input框type类型为file
ps:注意,此处会有一个问题,可能有些同学也可能会遇到,input框type类型为file之后,框架的样式就全都没了,变成了很原始的样子,但是项目肯定不能那么丑哇,于是我是这样解决滴。
(1)写了一个a标签包在input之外,将a标签样式模拟成按钮
.virtual-upload-btn {
padding: 4px 10px;
height: 20px;
line-height: 20px;
border: 1px solid#999;
border-radius: 5px;
text-decoration: none;
color: #fff;
position: relative;
top: 7px;
cursor: pointer;
}
(2)令input的opacity:0
(3)让input定位在a标签上(子绝父相)
.real-upload-btn {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
以上便可以自己模仿一个上传文件的按钮了。
(3)模仿上传后显示文件
在a标签后手动增加了一个span标签
布局如下:
<div class="col-md-8" style="top:50%;">
<a href="javascript:;" class="virtual-upload-btn">
选择文件
<input type="file" @change="upload" id="fileExport" class='real-upload-btn' accept=".pdf">
</a>
<span id="file-name" style="display: inline-block;position: absolute;padding: 6px 0px 6px 6px;width: 75%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;">{{fileName}}</span>
</div>
给按钮设置onchange事件,当有文件时,让文件名显示在按钮其后
js如下:
upload(){
let files = $('#fileExport').prop('files');
if (files.length < 1) {
return layer.msg('请选择导入文件!');
}else{
this.fileName=files[0].name
}
},
2.ajax代码
$.ajax({
async: false,
cache: false,
type: "POST",
data: formData,
dataType: 'JSON',
url: baseURL + '/plan-management-entity',
contentType: false, //必须
processData: false, //必须
success: function (result) {
// debugger
if (result.success) {
layer.msg(htl + '成功!');
_this.closeAddWin();
_this.getTableData();
} else {
layer.msg(htl + '失败!');
// console.log('失败');
}
},
error: function () {
layer.msg(htl + '失败!');
// console.log('错误');
}
});