欢迎访问笔者个人技术博客: http://rukihuang.xyz/ 后端 9月初,接到单位领导的任务,要求实现一个在线教育平台,主要展示岗位教学视频,以及相关的作业指导书,并建议要配套一个后台系统方便文件的上传和管理。作为后端开发,决定使用前后端分离,前端使用vue-admin-element,后端使用Springboot+MyBatis,数据库使用Mysql,容器使用tomcat,以及部署vue项目需要的nginx,jdk使用1.8由于项目开发只有我一个人,开发过程中遇到了不少问题,但所幸都一一解决了,趁着摸鱼的空档,决定将遇到的问题和解决方法记录下来,方便之后查阅。 1. SpringBoot实现文件上传 参考的是这篇掘金的文章,很详细。SpringBoot实现文件上传 1.1 配置类 UploadConfig 限制上传文件大小,以及总的请求文件大小。
/**
* @author :RukiHuang
* @description:文件上传配置类
* 配置MaxFileSize等属性
* @date :2022/9/2 9:45
*/
@Configuration
public class UploadConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个数据大小
factory.setMaxFileSize(DataSize.ofMegabytes(200));
//总上传文件的大小
factory.setMaxRequestSize(DataSize.ofGigabytes(10));
return factory.createMultipartConfig();
}
}
也可以通过在 application.properties
配置文件中指定
#文件上传
# 文件大小设置已在UploadConfig中配置,也可在配置文件中配置
#单个文件大小
spring.servlet.multipart.max-file-size=200MB
#总文件大小(允许存储文件的文件夹大小)
spring.servlet.multipart.max-request-size=10240MB
1.2 配置文件 application.properties
指定文件上传目标路径以及允许的文件类型
#文件上传的目标路径
file.upload.path=G:\temp\
#文件上传允许的类型
file.upload.allowType[0]=application/pdf
file.upload.allowType[1]=video/mp4
1.3 配置文件读取 UploadProperties
/**
* @author :RukiHuang
* @description:文件上传
* 上传路径
* 文件格式
* @date :2022/9/2 10:05
*/
@Component
@ConfigurationProperties(prefix = "file.upload")
public class UploadProperties {
private String path;
private List<String> allowTypeList;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<String> getAllowType() {
return allowTypeList;
}
public void setAllowType(List<String> allowTypeList) {
this.allowTypeList = allowTypeList;
}
}
1.4 工具类
1.4.1 唯一ID生成器 IDUtils
生成唯一id
/**
* @author :RukiHuang
* @description:唯一ID生成器
* @date :2022/9/2 10:07
*/
public class IDUtils {
public static String generateUniqueId() {
return UUID.randomUUID().toString() + System.currentTimeMillis();
}
}
1.4.2 文件名替换工具 UploadUtils
替换原始文件名,避免文件名重复
/**
* @author :RukiHuang
* @description:文件名替换工具 避免文件名重复
* @date :2022/9/2 10:09
*/
public class UploadUtils {
public static String generateFileName(String oldName) {
String suffix = oldName.substring(oldName.lastIndexOf("."));
return IDUtils.generateUniqueId() + suffix;
}
}
1.5 web层 CoursewareController
/**
* @author :RukiHuang
* @description:课件的Controller
* @date :2022/9/1 13:37
*/
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/forum")
@RestController
public class CoursewareController {
private static Logger logger = LoggerFactory.getLogger(DocController.class);
@Autowired
CoursewareService coursewareService;
@Autowired
UploadService uploadService;
@RequestMapping("/coursewareUpload/uploadCourseware")
public ResponseResult uploadVideo(
@RequestParam("file") MultipartFile file
) {
String filename = null;
try {
filename = uploadService.uploadCourseware(file);
return ResponseResult.ok(filename, "课件上传成功");
} catch (IOException e) {
logger.error(e.getMessage());
return ResponseResult.failed(e.getMessage(),"课件上传失败");
}
}
@RequestMapping(value = "/coursewareUpload/submitCoursewareInfo", method = RequestMethod.POST)
public ResponseResult submitCoursewareInfo(
@RequestParam(name = "serverFileName")String serverFileName) {
try {
coursewareService.addCoursewareInfo(serverFileName);
return ResponseResult.ok("提交成功");
} catch (Exception e) {
logger.error(e.getMessage());
return ResponseResult.failed(e.getMessage(), "提交失败");
}
}
}
1.6 service层 UploadService CoursewareService
UploadService
/**
* @author :RukiHuang
* @description:上传service
* @date :2022/9/2 10:16
*/
@Service
public class UploadServiceImpl implements UploadService {
@Autowired
UploadProperties uploadProperties;
@Override
public String uploadCourseware(MultipartFile file) throws IOException {
System.out.println(file.getContentType());
if(!uploadProperties.getAllowType().get(0).equals(file.getContentType())) {
throw new IOException("课件上传类型错误");
}
String fileName = UploadUtils.generateFileName(file.getOriginalFilename());
File newFile = new File(uploadProperties.getPath()+"\courseware\" + fileName);//当前是在windows目录,部署到linux路径要修改为/courseware
file.transferTo(newFile);
System.out.println(newFile.getPath());
return fileName;
}
}
CoursewareService
/**
* @author :RukiHuang
* @description:课件service
* @date :2022/9/1 13:42
*/
@Service
public class CoursewareServiceImpl implements CoursewareService {
@Autowired
CoursewareDao coursewareDao;
@Override
public void addCoursewareInfo(String serverFileName) throws Exception {
String[] nameArray = serverFileName.split(" / ");
String coursewareName = nameArray[0];
String serverStorageName = nameArray[1];
String storagePath = "courseware/" + serverStorageName;
CoursewareInfoDto coursewareInfoDto = new CoursewareInfoDto(coursewareName, storagePath);
coursewareDao.addCoursewareInfo(coursewareInfoDto);
}
}
1.7 PostMan测试文件上传
第一步,头文件置空
第二步,请求体中选择上传文件
前端
2. Vue实现文件上传
2.1 单文件上传
2.1.1 业务逻辑
先对文件进行校验,判断文件大小以及类型是否符合要求。将文件上传至服务器。服务器返回新文件名和存储路径将文件名称和服务器名称提交至服务器,并将存储路径传入至数据库。组件使用的是vue-admin-template自带的iView,iView官方文档
2.1.2 代码实现
点击或拖拽文件至此
文档限制pdf格式,视频限制mp4格式(大小不超过200MB)
上传文件: {{ file.name }}
2.2 一个页面多处地方需要文件上传
2.2.1 业务逻辑
iview无法实现单个页面多处地方文件上传,file
会被替换使用原生的上传组件进行上传。
2.2.2 代码实现
作业指导书:
SOC文档:
教学视频:
工段岗位:
岗位职责:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)