layui上传文件怎么用
时间: 2023-09-13 07:04:05 浏览: 55
在使用 layui 上传文件前,需要引入 layui 的上传模块:
```html
<link rel="stylesheet" href="/layui/css/layui.css">
<script src="/layui/layui.js"></script>
```
然后在 HTML 中添加一个上传按钮:
```html
<div class="layui-upload">
<button type="button" class="layui-btn" id="uploadBtn">上传文件</button>
</div>
```
在 JavaScript 中,使用 layui.upload 模块的 render 方法初始化上传组件:
```javascript
layui.use('upload', function(){
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#uploadBtn', //绑定元素
url: '/upload/', //上传接口
done: function(res){
//上传完毕回调
console.log(res);
},
error: function(){
//请求异常回调
console.log('上传失败');
}
});
});
```
其中,`elem` 参数指定了上传按钮的 ID,`url` 参数指定了上传文件的接口地址,`done` 回调函数在上传成功后被调用,`error` 回调函数在上传失败时被调用。
完整代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui上传文件示例</title>
<link rel="stylesheet" href="/layui/css/layui.css">
<script src="/layui/layui.js"></script>
</head>
<body>
<div class="layui-upload">
<button type="button" class="layui-btn" id="uploadBtn">上传文件</button>
</div>
<script>
layui.use('upload', function(){
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#uploadBtn', //绑定元素
url: '/upload/', //上传接口
done: function(res){
//上传完毕回调
console.log(res);
},
error: function(){
//请求异常回调
console.log('上传失败');
}
});
});
</script>
</body>
</html>
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)