前端关键在于获取元素,本文现所写皆为原生开发,后续会将组件库例子进行补充
前端代码,ajax
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax上传图片练习</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<style type="text/css">
</style>
</head>
<body>
<form id="form">
<label for="exampleInputEmail1">身份证正面</label>
<input type="file" id="image" name="image" onchange="picture(this);" />
<!-- 这个image是参数名称,后台接收的字段名,根据需要更改 -->
<!-- 这个image是参数名称,后台接收的字段名,根据需要更改 -->
<!-- 这个image是参数名称,后台接收的字段名,根据需要更改 -->
<!-- 上传图片的路径 -->
<!-- <input type="hidden" name="" id="front" value="" /> -->
<!-- <div id="result"></div> -->
</form>
</body>
</html>
<script>
//正面身份证
function picture() {
var data = new FormData($('#form')[0]);
/* new FormData 的意思
* 获取我们for表单中的所有input的name和value为了更方便传值
* https://segmentfault.com/a/1190000012327982?utm_source=tag-newest
*/
console.log(data);
$.ajax({
url: "",
type: 'POST',
data: data,
dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
</script>
前端axios
//html
<input class="file" name="image" type="file" accept="image/png,image/gif,image/jpeg" @change="update($event)" />
//js
update(e) {
let file = e.target.files[0];
let param = new FormData(); //创建form对象
param.append('image', file, file.name); //通过append向form对象添加数据
//这个image是参数名称,后台接收的字段名,根据需要更改
//这个image是参数名称,后台接收的字段名,根据需要更改
//这个image是参数名称,后台接收的字段名,根据需要更改
this.$axios({
method: 'post',
url: '',
data: param
})
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log(err);
});
}
小程序(uniapp)
注意:uniapp开发的h5在浏览器会出现跨域的报错,但在内置浏览器中可用
已解决跨域问题:
跨域解决方法
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.uploadFile({
url: '', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'image',//参数名,后台接收的字段名,根据需要更改
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
}
});
}
});
后端 tp6
public function head_upload(){
// 获取表单上传文件 例如上传了001.jpg
$url='';//域名拼接用
$file = request()->file('image');
if(empty($file)){
echo json_encode(['status' => 2, 'msg' => '无文件']);
die();
}
// 上传到本地服务器
$savename = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
echo json_encode(['status' => 1, 'msg' => '请求成功','img'=>$url.$savename]);//拼接不需要则去掉
die();
}