前言:近期做網(wǎng)站項(xiàng)目遇到一個(gè)小功能刮便,實(shí)現(xiàn)網(wǎng)站用戶自定義上傳頭像,中間踩了很多坑绽慈,所以拿來分享一下恨旱,有涉及該類技術(shù)問題(SpringBoot項(xiàng)目文件上傳)可參考一下
1.開發(fā)前準(zhǔn)備
SpringBoot項(xiàng)目,SpringBoot基礎(chǔ)
-
zyupload插件(可去資源網(wǎng)站下載)
zyupload MySql 數(shù)據(jù)庫坝疼,自己定義用戶表(包含頭像路徑字段即可)
maven相關(guān)依賴 (僅展示io操作bufen)
<!--io流-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
- 數(shù)據(jù)庫字段可參照下面 實(shí)體類 創(chuàng)建(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>
* * 用戶實(shí)體類
* * </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 = "登錄時(shí)間")
private Date loginDate;
@ApiModelProperty(value = "創(chuàng)建時(shí)間")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "修改時(shí)間")
@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 {
/**
* 資源存儲(chǔ)根路徑
*/
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 格式單個(gè)圖片上傳仪芒,最大1MB(*^_^*)~
</blockquote>
<div id="zyupload" class="zyupload"></div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
// 初始化插件
$("#zyupload").zyUpload({
width: "650px", // 寬度
height: "400px", // 寬度
itemWidth: "140px", // 文件項(xiàng)的寬度
itemHeight: "120px", // 文件項(xiàng)的高度
url: "/user/avatarUpload", // 上傳文件的路徑
fileType: ["jpg", "png"],// 上傳文件的類型
fileSize: 1048576, // 上傳文件的大小
multiple: false, // 是否可以多個(gè)文件上傳
dragDrop: true, // 是否可以拖動(dòng)上傳文件
tailor: true, // 是否可以裁剪圖片
del: true, // 是否可以刪除文件
finishDel: true, // 是否在上傳文件完成后刪除預(yù)覽
/* 外部獲得的回調(diào)接口 */
onSelect: function (selectFiles, allFiles) { // 選擇文件的回調(diào)方法 selectFile:當(dāng)前選中的文件 allFiles:還沒上傳的全部文件
/* console.info("當(dāng)前選擇了以下文件:");
console.info(selectFiles);*/
},
onDelete: function (file, files) { // 刪除一個(gè)文件的回調(diào)方法 file:當(dāng)前刪除的文件 files:刪除之后的文件
alert("當(dāng)前刪除了圖片:" + file.name);
},
onSuccess: function (file, response) { // 文件上傳成功的回調(diào)方法
alert("頭像上傳成功:"+file.name);
//$("#uploadInf").append("<p>上傳成功,文件地址是:" + response + "</p>");
},
onFailure: function (file, response) { // 文件上傳失敗的回調(diào)方法
alert("頭像上傳失敗:" + file.name);
},
onComplete: function (response) { // 上傳完成的回調(diào)方法
alert("頭像上傳完成掂名!");
}
});
return false;
});
</script>
4.根據(jù)前端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: 修改數(shù)據(jù)庫頭像位置信息
User user = (User) request.getSession().getAttribute(LoginUser.LOGIN_USER_SESSION);
// 獲取本地靜態(tài)資源路徑
String localPath = "/staticmv/avatar/" + uidFile;
user.setAvatar(localPath);
userService.updateById(user);
return "頭像上傳成功";
} catch (IOException e) {
e.printStackTrace();
}
return "頭像上傳失斁萆颉!";
}
}
5. 最關(guān)鍵饺蔑,配置SpringBoot 靜態(tài)資源路徑映射
- 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配置
#對外暴露 靜態(tài)資源接口
file:
uploadFloder: D:/resources/
staticAccessPath: /static/**
common:
uploadWindow: D:\resources\
6.可以測試了┗|`O′|┛ 嗷~~
(1).上傳圖片
界面.jpg
選擇文件.jpg
(2). mybatis-plus 控制臺(tái)打印日志(更新數(shù)據(jù)庫)
日志
數(shù)據(jù)庫字段修改
(3). 刷新頁面锌介,展示成果 ( :
頭像上傳成功
本地目錄
ps:文中相關(guān)資源可私信作者獲取~