前端文件表单/ajax上传实例代码
表单上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试文件上传</title>
</head>
<body>
<form action="/attach/upload" enctype="multipart/form-data" method="post">
<input type="file" name="content" /> <br>
<input type="submit" value="上传" />
</form>
</body>
</html>
ajax文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试ajax文件上传</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css"/>
<style>
.upload_image_input_trigger {
position: relative;
display: inline-block;
margin-left: 10px;
margin-right: 10px;
overflow: hidden;
}
.upload_image_input {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
}
.box {
width:600px;
margin: 50px auto;
}
</style>
</head>
<body>
<div class="box">
<a href="javascript:;" style="margin-top:-4px;" class="btn btn-default upload_image_input_trigger">
<span>上传图片</span>
<input class="upload_image_input" type="file" accept=".png, .jpg, .jpeg">
</a>
</div>
<script>
$(function(){
$(".upload_image_input").on('change',function(){
var cur_obj = $(this);
var file_obj = this.files[0];
if(file_obj === undefined){
layer.msg('没有选择文件');
return;
}
if (file_obj.size > 2097152) {
layer.msg("图片大小不能超过2M");
return;
}
var formData = new FormData();
formData.append("type", "image");//其它参数
formData.append("content", file_obj);//文件对象
$.ajax({
url: '/attach/upload',
type: 'POST',
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
cur_obj.parent().find('span').html('上传中');
},
success: function(result){
console.log(result);
cur_obj.parent().find('span').html('上传图片完成');
alert("success");
}
});
});
});
</script>
</body>
</html>
文件上传请求头
- base64上传
Content-Disposition: form-data; name="icon"; filename=""
Content-Type: application/octet-stream
- 文件流上传:
Content-Disposition: form-data; name="upload_file"; filename="007c1Ibkgy1g58mg18i78j30u01hcwy4.jpg"
Content-Type: image/jpeg
- 表单提交
Content-Type: application/x-www-form-urlencoded
ps
file input表单,的父级元素一定要设置 position: relative
如果不设置 ,input file这样设置样式: style="position: absolute;top: 0;left: 0; right: 0;bottom: 0;opacity: 0;"
事件触发是整个页面位置
<a class="btn btn-info" style="position: relative;" href="javascript:;" >
<span>上传文件</span>
<input type="file" style="position: absolute;top: 0;left: 0; right: 0;bottom: 0;opacity: 0;" accept=".xlsx">
</a>