formData文件上传--案例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<table>
		<form id="uploadForm" enctype="multipart/form-data">
		    <input id="file" type="file" name="file"/>
		    <button id="upload" type="button">upload</button>
		</form>
	</table>
</body>
</html>
<script src="jquery.1.12.min.js"></script>
<script>
$("#upload").click(function(){
		$.ajax({
	    url: 'upload.php',
	    type: 'POST',
	    cache: false,
	    data: new FormData($('#uploadForm')[0]),
	    processData: false,
	    contentType: false
	}).done(function(res) {
		alert(res)
	}).fail(function(res) {});
})

</script>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于 Element UI 中的 el-upload 组件上传文件并携带参数的案例: ```html <template> <div> <el-upload class="upload-demo" action="/api/upload" :headers="headers" :multiple="false" :data="formData" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" :on-exceed="handleExceed" :limit="limit" :file-list="fileList" > <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </div> </template> <script> export default { data() { return { headers: { Authorization: 'Bearer ' + localStorage.getItem('token'), }, limit: 1, fileList: [], formData: { type: 'avatar', }, }; }, methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!'); } if (!isLt500K) { this.$message.error('上传头像图片大小不能超过 500KB!'); } return isJPG && isLt500K; }, handleExceed(files, fileList) { this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,已自动过滤多余的文件`); }, handleSuccess(response, file, fileList) { this.$message.success('上传成功'); }, handleError(error, file, fileList) { this.$message.error('上传失败,请重试'); }, }, }; </script> ``` 在这个案例中,我们使用了以下属性: - `action`:上传文件的地址; - `headers`:请求头部信息,此处使用了 JWT 鉴权; - `multiple`:是否支持多选文件; - `data`:上传文件时携带的参数; - `before-upload`:上传文件前的钩子函数,可以对文件类型、大小进行校验等操作; - `on-success` 和 `on-error`:上传成功和失败的回调函数; - `on-exceed`:超出文件数量限制的回调函数; - `limit`:限制上传文件数量; - `file-list`:已上传的文件列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值