1.文件上传前端代码
这里设置了文件上传框隐藏,点击图片会显示出来,在这里用的是上传图片并显示出来,其他类型文件也可,注意:ajax请求尽量用post,get类型有大小限制。
<img class="card-media" style="width:16rem;height:16rem"
src="<%=basePath%>static/images/userImage/测试.jpg"
onclick="openuploadMethod('${st.wiNum}')" alt="未上传头像"
onerror="javascript:this.src='<%=basePath%>static/images/userImage/未上传.jpg'" />
<div class="card-body" id="upbutton" style="display:none">
<form id="fileform" method="post" enctype="multipart/form-data">
<input id="upload" name="uploadfile" style="color:blue" type="file" >
<button class="icon-cloud-upload" onclick="uploadMethod()">点击上传</button>
</form>
</div>
其中οnerrοr="javascript:this.src=’<%=basePath%>static/images/userImage/未上传.jpg’"是图片加载失败显示图片
//打开文件上传界面
//打开文件上传
function openuploadMethod(wNum){
document.getElementById('upload').click();
$("#upbutton").show();
}
//上传头像
function uploadMethod(){
var form = new FormData(document.getElementById("fileform"));
$.ajax({
type:"post",
url:"http://localhost:8080/ssm/worker/upload",
data:form,
processData:false,
contentType:false,
async: false,
dataType:'text',
success:function(data){
if(data>0){
alert("上传成功")
window.location.reload();
return;
}
alert("请选择文件")
}
});
}
**2.后端代码**
```java
/**
* 上传图片
*/
@PostMapping("/upload")
@ResponseBody
public int testupload(@RequestParam("uploadfile") MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
if(!file.isEmpty()) {
//上传文件路径
String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
String path = classpath.replaceAll("WEB-INF/classes/", "")/*后面部分是工程文件目录,自定义*/+"static/images/userImage/";
//上传文件名
//String filename = file.getOriginalFilename();/*这个是上传文件的原文件名*/
//自定义生成文件名
String filename=测试.jpg
File filepath = new File(filename);
//判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//上传
file.transferTo(filepath);
return 1;
} else {
return 0;
}
}
完成!!!下次再弄文件下载代码