姜钧瀚第一次提交 文件上传下载

master
小萌新 6 months ago
parent d4966a4587
commit 90201ce300
  1. 7
      pom.xml
  2. 3
      src/main/java/com/teaching/TeachingBackendApplication.java
  3. 137
      src/main/java/com/teaching/backend/controller/CommonController.java
  4. 18
      src/main/java/com/teaching/backend/mapper/FileTableMapper.java
  5. 18
      src/main/java/com/teaching/backend/mapper/UserMapper.java
  6. 32
      src/main/java/com/teaching/backend/model/entity/FileTable.java
  7. 26
      src/main/java/com/teaching/backend/model/entity/User.java
  8. 22
      src/main/java/com/teaching/backend/service/FileTableService.java
  9. 16
      src/main/java/com/teaching/backend/service/UserService.java
  10. 90
      src/main/java/com/teaching/backend/service/impl/FileTableServiceImpl.java
  11. 24
      src/main/java/com/teaching/backend/service/impl/UserServiceImpl.java
  12. 4
      src/main/resources/application.properties
  13. 11
      src/main/resources/application.yml
  14. 76
      src/main/resources/static/hello.html
  15. 52
      src/main/resources/static/hello2.html
  16. 3
      src/main/resources/static/plugins/axios/axios.min.js
  17. 0
      src/main/resources/static/plugins/element-ui/fonts/element-icons.ttf
  18. 0
      src/main/resources/static/plugins/element-ui/fonts/element-icons.woff
  19. 1
      src/main/resources/static/plugins/element-ui/index.css
  20. 1
      src/main/resources/static/plugins/element-ui/index.js
  21. 11965
      src/main/resources/static/plugins/vue/vue.js
  22. 100
      src/test/java/com/teaching/TeachingBackendApplicationTests.java

@ -29,6 +29,13 @@
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- freemarker jar -->
<dependency>
<groupId>org.freemarker</groupId>

@ -10,6 +10,9 @@ public class TeachingBackendApplication {
public static void main(String[] args) {
SpringApplication.run(TeachingBackendApplication.class, args);
}
}

@ -0,0 +1,137 @@
package com.teaching.backend.controller;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.teaching.backend.common.BaseResponse;
import com.teaching.backend.common.ResultUtils;
import com.teaching.backend.model.entity.FileTable;
import com.teaching.backend.service.FileTableService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;
/**
* ClassName: CommonController
* Package: com.teaching.backend.controller
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/1 10:30
* @Version 1.0
*/
@RestController
public class CommonController {
@Resource
private FileTableService fileTableService;
@Value("${teaching-backend.img.path}")
private String basePath;
@Value("${teaching-backend.video.path}")
private String videoPath;
@PostMapping("/upload")
public BaseResponse<String> upload(@RequestParam("courseId") String courseId, MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String subDir;
if (suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".jpeg") || suffix.equalsIgnoreCase(".png")) {
subDir = "img/";
} else if (suffix.equalsIgnoreCase(".mp4") || suffix.equalsIgnoreCase(".avi") || suffix.equalsIgnoreCase(".mov")) {
subDir = "video/";
} else {
subDir = "others/";
}
File dir = new File(basePath + subDir);
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
file.transferTo(Paths.get(basePath, subDir, fileName).toFile());
String filePath = subDir + fileName;
fileTableService.updateFile(courseId, fileName, filePath);
System.out.println("文件的地址是:" + subDir + fileName);
return ResultUtils.success(filePath);
}
//文件下载
@GetMapping("/download")
public void download(@RequestParam String courseId, HttpServletResponse response) {
System.out.println(courseId);
System.out.println("在这我执行了下载的方法");
fileTableService.download(courseId, response, basePath);
}
}
// @GetMapping("/download")
// public void download(@RequestParam String fileName, HttpServletResponse response) {
//
// System.out.println("在这我执行了下载的方法");
// try {
//
//
// System.out.println("要下载的文件是:" + basePath + fileName);
//
// FileInputStream fileInputStream = new FileInputStream(new File(basePath ,fileName));
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// response.setContentType("application/octet-stream");
// response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//
// byte[] buffer = new byte[1024];
// int len;
// while ((len = fileInputStream.read(buffer)) > 0) {
// outputStream.write(buffer, 0, len);
// }
//
// outputStream.flush();
// outputStream.close();
// fileInputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }

@ -0,0 +1,18 @@
package com.teaching.backend.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.teaching.backend.model.entity.FileTable;
import org.apache.ibatis.annotations.Mapper;
/**
* ClassName: FileTableMapper
* Package: com.teaching.backend.mapper
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/4 11:51
* @Version 1.0
*/
@Mapper
public interface FileTableMapper extends BaseMapper<FileTable> {
}

@ -0,0 +1,18 @@
package com.teaching.backend.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.teaching.backend.model.entity.User;
import org.apache.ibatis.annotations.Mapper;
/**
* ClassName: UserMapper
* Package: com.teaching.backend.mapper
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/3 17:47
* @Version 1.0
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

@ -0,0 +1,32 @@
package com.teaching.backend.model.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.stream.Stream;
/**
* ClassName: FileTable
* Package: com.teaching.backend.model.entity
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/4 11:48
* @Version 1.0
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@TableName("filetable")
public class FileTable {
private int id;
private String courseId;
private String fileName;
private String filePath;
}

@ -0,0 +1,26 @@
package com.teaching.backend.model.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* ClassName: User
* Package: com.teaching.backend.model.entity
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/3 17:42
* @Version 1.0
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private int userid;
private int bokeid;
private int type;
}

@ -0,0 +1,22 @@
package com.teaching.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.teaching.backend.model.entity.FileTable;
import javax.servlet.http.HttpServletResponse;
/**
* ClassName: FileTableService
* Package: com.teaching.backend.service
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/4 11:49
* @Version 1.0
*/
public interface FileTableService extends IService<FileTable> {
void updateFile(String courseId, String fileName, String filePath);
void download(String courseId, HttpServletResponse response, String basePath);
}

@ -0,0 +1,16 @@
package com.teaching.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.teaching.backend.model.entity.User;
/**
* ClassName: UserService
* Package: com.teaching.backend.service
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/3 17:48
* @Version 1.0
*/
public interface UserService extends IService<User> {
}

@ -0,0 +1,90 @@
package com.teaching.backend.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teaching.backend.mapper.FileTableMapper;
import com.teaching.backend.model.entity.FileTable;
import com.teaching.backend.service.FileTableService;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* ClassName: FileTableImpl
* Package: com.teaching.backend.service.impl
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/4 11:50
* @Version 1.0
*/
@Service
public class FileTableServiceImpl extends ServiceImpl<FileTableMapper,FileTable> implements FileTableService {
@Override
public void updateFile(String courseId, String fileName, String filePath) {
System.out.println("执行了service中的方法");
System.out.println(courseId);
System.out.println(fileName);
System.out.println(filePath);
FileTable fileTable=new FileTable();
fileTable.setFileName(fileName);
fileTable.setFilePath(filePath);
UpdateWrapper<FileTable> fileTableUpdateWrapper=new UpdateWrapper<>();
fileTableUpdateWrapper.in("id",courseId);
this.update(fileTable,fileTableUpdateWrapper);
}
@Override
public void download(String courseId, HttpServletResponse response, String basePath) {
try {
FileTable courseFile = this.getById(courseId);
System.out.println(courseFile);
if (courseFile != null) {
String fileName = courseFile.getFileName();
String filePath = courseFile.getFilePath();
System.out.println("要下载的文件是:" + basePath + filePath);
File file = new File(basePath, filePath);
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
fileInputStream.close();
outputStream.close();
} else {
System.out.println("文件不存在");
}
} else {
System.out.println("文件不存在或未找到相关记录");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,24 @@
package com.teaching.backend.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teaching.backend.mapper.UserMapper;
import com.teaching.backend.model.entity.User;
import com.teaching.backend.service.UserService;
import org.springframework.stereotype.Service;
/**
* ClassName: UserServiceImpl
* Package: com.teaching.backend.service.impl
* Description:
*
* @Author 姜钧瀚
* @Create 2024/6/3 17:48
* @Version 1.0
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

@ -0,0 +1,4 @@
teaching-backend.img.path=C:\\Users\\jian\\Desktop\\cc\\teaching-backend\\src\\main\\resources\\static\\
teaching-backend.video.path=C:\\Users\\jian\\Desktop\\cc\\teaching-backend\\src\\main\\resources\\static\\video\\
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

@ -19,14 +19,3 @@ mybatis:
- classpath*:com/**/mapper/*.xml
# 接口文档配置
knife4j:
enable: true
openapi:
title: "接口文档"
version: 1.0
group:
default:
api-rule: package
api-rule-resources:
- com.teaching.backend.controller

@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传下载示例</title>
</head>
<body>
<div id="app">
<h1>文件上传</h1>
<form @submit.prevent="upload" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传文件</button>
</form>
<h1>文件下载</h1>
<button @click="download">点击下载文件</button>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
fileName: ''
},
methods: {
download() {
axios.get('/download?fileName=' + this.fileName, { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', this.fileName);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
})
.catch(error => {
console.error("出错了", error);
});
},
upload(event) {
let formData = new FormData();
formData.append('file', event.target.elements.file.files[0]);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log("上传成功,文件名为:" + response.data.data);
this.fileName = response.data.data;
})
.catch(error => {
console.error('上传失败', error);
});
}
}
});
</script>
</body>
</html>

@ -0,0 +1,52 @@
<!DOCTYPE html>
<html>
<head>
<title>视频上传和下载</title>
</head>
<body>
<div id="app2">
<input type="file" ref="fileInput" @change="handleFileChange">
<button @click="uploadFile">上传</button>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script>
new Vue({
el: '#app2',
data: {
selectedFile:''
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0];
},
uploadFile() {
const formData = new FormData();
formData.append('file', this.selectedFile);
// 发送文件上传请求
axios.post('/video/upload', formData)
.then(response => {
// 处理上传成功的响应
console.log(response.data);
})
.catch(error => {
// 处理上传失败的错误
console.error(error);
});
}
}
});
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

@ -1,13 +1,113 @@
package com.teaching;
import com.teaching.backend.common.BaseResponse;
import com.teaching.backend.common.ResultUtils;
import com.teaching.backend.model.entity.User;
import com.teaching.backend.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import java.sql.SQLOutput;
import java.util.*;
@SpringBootTest
class TeachingBackendApplicationTests {
@Resource
UserService userService;
@Test
void contextLoads() {
//获取用户集合
List<User> userList=userService.list() ;
System.out.println("这是用户集合表"+userList);
//将数据存进map集合中
Map<Integer,Map<Integer,Integer>> userBlogLikes=new HashMap<>();
//遍历userList集合
for (User user:userList){
int userId = user.getUserid();
int bokeId = user.getBokeid();
int type = user.getType();
userBlogLikes.computeIfAbsent(userId, k -> new HashMap<>()).put(bokeId, type);
}
System.out.println("这是用户集合的map表:"+userBlogLikes);
// 选择一个用户
int userId = 1;
// 找到与该用户相似度最高的用户
int mostSimilarUser = findMostSimilarUser(userId, userBlogLikes);
if (mostSimilarUser < 0) {
System.out.println("No similar user found.");
return;
}
System.out.println("这是相似度最高的用户"+mostSimilarUser);
// 根据相似用户的点赞记录推荐博客
Set<Integer> recommendedBlogs = recommendBlogs(userId, mostSimilarUser, userBlogLikes);
System.out.println("Recommended blogs for user " + userId + ": " + recommendedBlogs);
}
public static int findMostSimilarUser(int userId, Map<Integer, Map<Integer, Integer>> userBlogLikes) {
int mostSimilarUser = -1;
int maxSimilarity = 0;
Map<Integer, Integer> targetUserLikes = userBlogLikes.get(userId);
for (Map.Entry<Integer, Map<Integer, Integer>> entry : userBlogLikes.entrySet()) {
if (entry.getKey() != userId) {
int similarity = calculateSimilarity(targetUserLikes, entry.getValue());
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
mostSimilarUser = entry.getKey();
}
}
}
return mostSimilarUser;
}
public static int calculateSimilarity(Map<Integer, Integer> user1Likes, Map<Integer, Integer> user2Likes) {
int similarity = 0;
for (Map.Entry<Integer, Integer> entry : user1Likes.entrySet()) {
int blogId = entry.getKey();
if (user2Likes.containsKey(blogId) && user2Likes.get(blogId) == 1) {
similarity++;
}
}
return similarity;
}
public static Set<Integer> recommendBlogs(int userId, int similarUserId, Map<Integer, Map<Integer, Integer>> userBlogLikes) {
Set<Integer> recommendedBlogs = new HashSet<>();
Map<Integer, Integer> targetUserLikes = userBlogLikes.get(userId);
Map<Integer, Integer> similarUserLikes = userBlogLikes.get(similarUserId);
for (Map.Entry<Integer, Integer> entry : similarUserLikes.entrySet()) {
int blogId = entry.getKey();
if (!targetUserLikes.containsKey(blogId) || targetUserLikes.get(blogId) == 0) {
recommendedBlogs.add(blogId);
}
}
return recommendedBlogs;
}
}

Loading…
Cancel
Save