前言:近期做網站項目遇到一個小功能,實現網站用戶自定義上傳頭像,中間踩了很多坑,所以拿來分享一下,有涉及該類技術問題(SpringBoot項目文件上傳)可參考一下
1.開發前準備
SpringBoot項目,SpringBoot基礎
-
zyupload插件(可去資源網站下載)
MySql 數據庫,自己定義用戶表(包含頭像路徑字段即可)
maven相關依賴 (僅展示io操作bufen)
<!--io流-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
- 數據庫字段可參照下面 實體類 創建(Mybatis-plus)
package com.ht.webfront.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.Version;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* * 用戶實體類
* * </p>
* *
* * @author 掌灬紋
* * @since 2021-03-11
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="User對象", description="")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "自增id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "用戶編號")
private String uid;
@ApiModelProperty(value = "角色編號")
private Integer roleId;
@ApiModelProperty(value = "用戶名")
private String username;
@ApiModelProperty(value = "密碼")
private String password;
@ApiModelProperty(value = "頭像")
private String avatar;
@ApiModelProperty(value = "登錄時間")
private Date loginDate;
@ApiModelProperty(value = "創建時間")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "修改時間")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
@ApiModelProperty(value = "版本號")
@Version
private Integer version;
@ApiModelProperty(value = "邏輯刪除")
@TableLogic
private Integer deleted;
}
2. 定義上傳路徑常量(常量信息提取)
package com.ht.webfront.persistence;
/**
* 資源路徑枚舉
*/
public class ResourceConst {
/**
* 資源存儲根路徑
*/
public static final String ROOT_PATH = "D:\\resources\\";
// 視頻文件
public static final String VIDEO = "video\\";
// 圖片
public static final String IMAGE = "image\\";
// 文檔 xls xlsx
public static final String DOCUMENT = "document\\";
// avatar 特定頭像存放位置
public static final String AVATAR = "avatar\\";
}
3.編寫簡易前端頁面 (含頭像展示,zyupload文件上傳插件即可,部分代碼示例)
<!--頭像上傳-->
<div class="col-md-9 blog-main">
<div class="layuimini-container">
<div class="layuimini-main">
<blockquote class="layui-elem-quote">
頭像上傳: <br>
僅支持 png jpg 格式單個圖片上傳,最大1MB(*^_^*)~
</blockquote>
<div id="zyupload" class="zyupload"></div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
// 初始化插件
$("#zyupload").zyUpload({
width: "650px", // 寬度
height: "400px", // 寬度
itemWidth: "140px", // 文件項的寬度
itemHeight: "120px", // 文件項的高度
url: "/user/avatarUpload", // 上傳文件的路徑
fileType: ["jpg", "png"],// 上傳文件的類型
fileSize: 1048576, // 上傳文件的大小
multiple: false, // 是否可以多個文件上傳
dragDrop: true, // 是否可以拖動上傳文件
tailor: true, // 是否可以裁剪圖片
del: true, // 是否可以刪除文件
finishDel: true, // 是否在上傳文件完成後刪除預覽
/* 外部獲得的回調接口 */
onSelect: function (selectFiles, allFiles) { // 選擇文件的回調方法 selectFile:當前選中的文件 allFiles:還沒上傳的全部文件
/* console.info("當前選擇了以下文件:");
console.info(selectFiles);*/
},
onDelete: function (file, files) { // 刪除一個文件的回調方法 file:當前刪除的文件 files:刪除之後的文件
alert("當前刪除了圖片:" + file.name);
},
onSuccess: function (file, response) { // 文件上傳成功的回調方法
alert("頭像上傳成功:"+file.name);
//$("#uploadInf").append("<p>上傳成功,文件地址是:" + response + "</p>");
},
onFailure: function (file, response) { // 文件上傳失敗的回調方法
alert("頭像上傳失敗:" + file.name);
},
onComplete: function (response) { // 上傳完成的回調方法
alert("頭像上傳完成!");
}
});
return false;
});
</script>
4.根據前端JS定義的上傳插件處理 URL路徑編寫控制器(/user/avatarUpload)
@Controller
public class UserController{
@ResponseBody
@PostMapping("/user/avatarUpload")
public String doUploadAvatar(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam("file") MultipartFile file
){
// 上傳根路徑
String rootPath = ResourceConst.ROOT_PATH + ResourceConst.AVATAR;
//文件名 後綴名
String filename = file.getOriginalFilename();
String suffix = filename.substring(filename.lastIndexOf("."));
// 唯一文件名
String uidFile = CupidUtils.getUuid() + suffix;
//System.out.println(rootPath + " : " + uidFile);
// 圖片上傳
File target = new File(rootPath,uidFile);
if (!target.exists()){
target.mkdirs();
}
try {
file.transferTo(target);
// todo: 修改數據庫頭像位置信息
User user = (User) request.getSession().getAttribute(LoginUser.LOGIN_USER_SESSION);
// 獲取本地靜態資源路徑
String localPath = "/staticmv/avatar/" + uidFile;
user.setAvatar(localPath);
userService.updateById(user);
return "頭像上傳成功";
} catch (IOException e) {
e.printStackTrace();
}
return "頭像上傳失敗!";
}
}
5. 最關鍵,配置SpringBoot 靜態資源路徑映射
- mvc-config 配置
package com.ht.webfront.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class SpringMVCConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/staticmv/**").addResourceLocations("file:///D:\\resources\\");
//addResourceHandlers(registry);
}
}
- yml配置
#對外暴露 靜態資源接口
file:
uploadFloder: D:/resources/
staticAccessPath: /static/**
common:
uploadWindow: D:\resources\
6.可以測試了┗|`O′|┛ 嗷~~
(1).上傳圖片
(2). mybatis-plus 控制檯打印日誌(更新數據庫)
(3). 刷新頁面,展示成果 ( :
ps:文中相關資源可私信作者獲取~