畢設終於寫到頭像上傳了,本來想用Vue寫來着,但是一直不順利,還是對Vue用的不太熟.所以就用jquery寫了.
首先添加以下標簽
<img id="avatarPreview" :src="user.avatar" alt="" title="點擊更換圖片" />
<input id="upload" name="file" type="file" accept="image/png,image/gif,image/jpeg,image/jpg" />
<button type="button" id="uploadphoto">上傳</button>
接下添加點擊事件
<script type="text/javascript">
$(function () {
$("#uploadphoto").hide();
//點擊選擇文件按鈕顯示上傳按鈕
$("#upload").click(function () {
$("#uploadphoto").show();
})
$('#uploadphoto').click(function () {
$("#uploadphoto").hide();
var file = document.getElementById("upload").files[0]
var param = new FormData() // 創建form對象
param.append('file', file) // 通過append向form對象添加數據
var config = {
// 添加請求頭 向后台傳入token, 這個multipart/form-data必需
headers: {'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + getUser().token}
}
axios.post('http://localhost:9002/user/uploadAvatar', param, config)
.then(res => {
if(res.data.flag){
vm.$data.user.avatar=res.data.data.url;
}
}).catch(res=>{
console.log(res)
})
})
})
</script>
后端:
//頭像上傳
@PostMapping("/uploadAvatar")
public Result uploadAvatar(@PathVariable MultipartFile file){
//判斷token的代碼就省略了
if(file.isEmpty()){
return new Result(false,StatusCode.ERROR,"請選擇文件");
}
String fileName = file.getOriginalFilename();//文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));//后綴名
String path = "E:/workspace/JavaEEWeb/tsemap-parent/tsemap-user/src/main/resources/static/img"; //文件存儲位置 我放在了我的項目下
fileName=UUID.randomUUID()+suffixName;//圖片名
File dest = new File(path+"/"+fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
String url="./img/"+fileName;
Map map=new HashMap();
map.put("url",url);
return new Result(true,StatusCode.OK,"上傳成功",map);
} catch (IOException e) {
e.printStackTrace();
}
return new Result(false,StatusCode.ERROR,"上傳失敗");
}
效果大概就是這樣:
點擊上傳:
大概就是這樣吧 bug還是有 后續等整個畢設寫完了再改細節吧