diff --git a/pom.xml b/pom.xml index 5f1d731..803f420 100644 --- a/pom.xml +++ b/pom.xml @@ -56,6 +56,13 @@ 3.5.2 + + + com.aliyun.oss + aliyun-sdk-oss + 3.15.1 + + mysql mysql-connector-java @@ -78,6 +85,7 @@ knife4j-openapi2-spring-boot-starter 4.4.0 + org.apache.commons diff --git a/src/main/java/com/teaching/backend/controller/CommonController.java b/src/main/java/com/teaching/backend/controller/CommonController.java index 855c769..00bb8d3 100644 --- a/src/main/java/com/teaching/backend/controller/CommonController.java +++ b/src/main/java/com/teaching/backend/controller/CommonController.java @@ -1,11 +1,16 @@ package com.teaching.backend.controller; +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.model.OSSObject; 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.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -17,10 +22,9 @@ 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.io.*; import java.nio.file.Paths; +import java.util.Date; import java.util.UUID; /** @@ -39,15 +43,23 @@ public class CommonController { @Resource private FileTableService fileTableService; - @Value("${teaching-backend.img.path}") - private String basePath; + @Value("${aliyun.oss.endpoint}") + private String endpoint; + + @Value("${aliyun.oss.accessKeyId}") + private String accessKeyId; + + @Value("${aliyun.oss.accessKeySecret}") + private String accessKeySecret; + + @Value("${aliyun.oss.bucketName}") + private String bucketName; - @Value("${teaching-backend.video.path}") - private String videoPath; @PostMapping("/upload") public BaseResponse upload(@RequestParam("courseId") String courseId, MultipartFile file) throws IOException { + OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); String originalFilename = file.getOriginalFilename(); @@ -62,67 +74,69 @@ public class CommonController { 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; + ossClient.putObject(bucketName, subDir + fileName, file.getInputStream()); - fileTableService.updateFile(courseId, fileName, filePath); + String objectUrl = ossClient.generatePresignedUrl(bucketName, subDir + fileName, new Date(System.currentTimeMillis() + 3600 * 1000)).toString(); + fileTableService.updateFile(courseId, fileName, objectUrl); // 更新文件路径为OSS生成的URL - System.out.println("文件的地址是:" + subDir + fileName); + ossClient.shutdown(); - return ResultUtils.success(filePath); + System.out.println("文件的地址是:" + objectUrl); + + return ResultUtils.success(objectUrl); } //文件下载 @GetMapping("/download") - public void download(@RequestParam String courseId, HttpServletResponse response) { + public BaseResponse download(@RequestParam String courseId, @RequestParam String path, HttpServletResponse response) throws IOException { + System.out.println("执行了下载的方法"); - System.out.println(courseId); - System.out.println("在这我执行了下载的方法"); + FileTable fileTable = fileTableService.getById(courseId); + System.out.println(fileTable); - fileTableService.download(courseId, response, basePath); + // 创建OSS客户端 + OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); - } -} + String key = extractKeyFromFullPath(fileTable.getFilePath()); + OSSObject object = ossClient.getObject(bucketName, key); + + String fileName = fileTable.getFileName(); -// @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(); -// } -// } + // 设置保存文件的路径 + String savePath = path + "/" + fileName; + // 获取文件的输入流 + InputStream inputStream = object.getObjectContent(); + + // 设置响应头 + response.setContentType("application/octet-stream"); + response.setHeader("Content-Disposition", "attachment; filename=" + fileName); + + // 创建保存文件 + File saveFile = new File(savePath); + + // 将文件内容复制到保存文件中 + FileUtils.copyInputStreamToFile(inputStream, saveFile); + + // 关闭输入流和OSS客户端 + inputStream.close(); + ossClient.shutdown(); + + return ResultUtils.success("成功"); + } + + private String extractKeyFromFullPath(String filePath) { + // 提取存储桶名称 + String key = filePath.substring(filePath.indexOf("com") + 4, filePath.indexOf("?")); + return key; + } +} diff --git a/src/main/java/com/teaching/backend/controller/WordController.java b/src/main/java/com/teaching/backend/controller/WordController.java new file mode 100644 index 0000000..3697ee0 --- /dev/null +++ b/src/main/java/com/teaching/backend/controller/WordController.java @@ -0,0 +1,66 @@ +package com.teaching.backend.controller; + +import com.teaching.backend.utils.WordUtil; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +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 java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +@RestController +public class WordController { + private String outputPath; + + @PostMapping("/Word/get") + public ResponseEntity createWord(@RequestParam("outputPath") String outputPath) { + String filename = "generatedWord.docx"; + System.out.println(outputPath); + WordUtil wordUtil = new WordUtil(); + // 设置模板文件存放的目录 + wordUtil.setBaseDir("C:\\Users\\jian\\Desktop\\123345\\"); + // 设置模板文件名称 + wordUtil.setTemplateFile("123.ftl"); + // 设置 Word 生成的输出目录 + wordUtil.setOutputDir(outputPath); + + Map dataMap = new HashMap<>(); + dataMap.put("username1", "姜钧瀚"); + + + + String generatedFilePath = wordUtil.createWord(dataMap); + if (generatedFilePath.equals("操作失败")) { + System.out.println("操作失败"); + return ResponseEntity.badRequest().body("操作失败".getBytes()); + } + + // 读取生成的 Word 文件内容 + File file = new File(generatedFilePath); + byte[] fileContent; + try { + fileContent = Files.readAllBytes(file.toPath()); + } catch (IOException e) { + e.printStackTrace(); + return ResponseEntity.badRequest().body("文件读取失败".getBytes()); + } + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); + headers.setContentDispositionFormData("attachment", filename); + + //返回word文件 + return new ResponseEntity<>(fileContent, headers, HttpStatus.OK); + + } + + +} diff --git a/src/main/java/com/teaching/backend/mapper/courses/CoursesMapper.java b/src/main/java/com/teaching/backend/mapper/courses/CoursesMapper.java index 14d3764..d3574bf 100644 --- a/src/main/java/com/teaching/backend/mapper/courses/CoursesMapper.java +++ b/src/main/java/com/teaching/backend/mapper/courses/CoursesMapper.java @@ -2,6 +2,7 @@ package com.teaching.backend.mapper.courses; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.teaching.backend.model.entity.courses.Courses; +import org.apache.ibatis.annotations.Mapper; /** *

@@ -11,6 +12,7 @@ import com.teaching.backend.model.entity.courses.Courses; * @author zjh * @since 2024-05-30 */ +@Mapper public interface CoursesMapper extends BaseMapper { } diff --git a/src/main/java/com/teaching/backend/service/FileTableService.java b/src/main/java/com/teaching/backend/service/FileTableService.java index 46fbb04..4499d92 100644 --- a/src/main/java/com/teaching/backend/service/FileTableService.java +++ b/src/main/java/com/teaching/backend/service/FileTableService.java @@ -3,8 +3,6 @@ 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 @@ -18,5 +16,10 @@ public interface FileTableService extends IService { void updateFile(String courseId, String fileName, String filePath); - void download(String courseId, HttpServletResponse response, String basePath); + + + + + + } diff --git a/src/main/java/com/teaching/backend/service/impl/FileTableServiceImpl.java b/src/main/java/com/teaching/backend/service/impl/FileTableServiceImpl.java index 63212b5..a4c3e07 100644 --- a/src/main/java/com/teaching/backend/service/impl/FileTableServiceImpl.java +++ b/src/main/java/com/teaching/backend/service/impl/FileTableServiceImpl.java @@ -7,12 +7,6 @@ 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 @@ -31,60 +25,82 @@ public class FileTableServiceImpl extends ServiceImpl System.out.println(fileName); System.out.println(filePath); - FileTable fileTable=new FileTable(); + FileTable fileTable = new FileTable(); fileTable.setFileName(fileName); fileTable.setFilePath(filePath); +// fileTable.setCourseId(courseId); // 设置主键值 +// +// this.save(fileTable); // 使用save方法来添加新的记录 + + UpdateWrapper fileTableUpdateWrapper = new UpdateWrapper<>(); + fileTableUpdateWrapper.eq("id", courseId); + + this.update(fileTable, fileTableUpdateWrapper); + + }} + + +// @Override +// public String getPath(String courseId, String basePath) { +// +// FileTable courseFile = this.getById(courseId); +// +// System.out.println("1111111111111111111111" + courseFile); +// +// String FileName = basePath + courseFile.getFilePath(); +// +// System.out.println("这是往前端方法返回的值" + FileName); +// return FileName; +// } + + +// @Override +// public void download(String courseId, HttpServletResponse response, String endpoint) { +// OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessSecret); +// +// 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(); +// } +// +// +//} - UpdateWrapper 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(); - } - } - } diff --git a/src/main/java/com/teaching/backend/utils/AliOssTest.java b/src/main/java/com/teaching/backend/utils/AliOssTest.java new file mode 100644 index 0000000..55f0f8f --- /dev/null +++ b/src/main/java/com/teaching/backend/utils/AliOssTest.java @@ -0,0 +1,68 @@ +package com.teaching.backend.utils; + +import com.aliyun.oss.ClientException; +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.OSSException; +import com.aliyun.oss.common.auth.CredentialsProviderFactory; +import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; +import com.aliyun.oss.model.PutObjectRequest; +import com.aliyun.oss.model.PutObjectResult; + +import java.awt.*; +import java.io.FileInputStream; +import java.io.InputStream; + +public class AliOssTest { + public static void main(String[] args) throws Exception { + // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。因为是华中地区 所以需要加上-lr + String endpoint = "oss-cn-wuhan-lr.aliyuncs.com"; + + // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 +// EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); + String accessKeyId ="LTAI5tFkdu3y5WddxbjgaG2F"; + String accessKeySecret ="1xUchxUTlmUBoTV5JQIrKsVjSkmsLF"; + + // 填写Bucket名称,例如examplebucket。 + String bucketName = "ceshi132132"; + // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 + String objectName = "ceshi/33.docx"; + // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 + // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。 + String filePath= "C:\\Users\\jian\\Desktop\\123345\\999\\33.docx"; + + // 创建OSSClient实例。 + OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); +// OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); + + + try { + InputStream inputStream = new FileInputStream(filePath); + // 创建PutObjectRequest对象。 + PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); + // 设置该属性可以返回response。如果不设置,则返回的response为空。 + putObjectRequest.setProcess("true"); + // 创建PutObject请求。 + PutObjectResult result = ossClient.putObject(putObjectRequest); + // 如果上传成功,则返回200。 + System.out.println(result.getResponse().getStatusCode()); + } catch (OSSException oe) { + System.out.println("Caught an OSSException, which means your request made it to OSS, " + + "but was rejected with an error response for some reason."); + System.out.println("Error Message:" + oe.getErrorMessage()); + System.out.println("Error Code:" + oe.getErrorCode()); + System.out.println("Request ID:" + oe.getRequestId()); + System.out.println("Host ID:" + oe.getHostId()); + } catch (ClientException ce) { + System.out.println("Caught an ClientException, which means the client encountered " + + "a serious internal problem while trying to communicate with OSS, " + + "such as not being able to access the network."); + System.out.println("Error Message:" + ce.getMessage()); + } finally { + if (ossClient != null) { + ossClient.shutdown(); + } + } + } +} + diff --git a/src/main/java/com/teaching/backend/utils/WordUtil.java b/src/main/java/com/teaching/backend/utils/WordUtil.java new file mode 100644 index 0000000..51d84dc --- /dev/null +++ b/src/main/java/com/teaching/backend/utils/WordUtil.java @@ -0,0 +1,84 @@ +package com.teaching.backend.utils; + +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import lombok.Data; + + +import java.io.*; +import java.net.URLDecoder; +import java.util.Map; +import java.util.Random; + +/** + * @Author:youhang + * @Date:2024-05-30-18:20 + * @Description: + */ +@Data +public class WordUtil { + + private Configuration configuration = null; + + /* + * 模板文件存放的目录 + */ + private String baseDir; + + /* + * 模板文件名称 + */ + private String templateFile; + + /* + * word生成的输出目录 + */ + private String outputDir; + + public WordUtil(){ + configuration = new Configuration(); + configuration.setDefaultEncoding("UTF-8"); + } + + /* + *

转换成word
+ */ + public String createWord(Map dataMap){ + + configuration.setClassForTemplateLoading(this.getClass(), "");//模板文件所在路径 + + Template t = null; + + try { + //得到模板文件 + configuration.setDirectoryForTemplateLoading(new File(baseDir)); + t = configuration.getTemplate(templateFile); + } catch (IOException e) { + e.printStackTrace(); + } + + //随机生成 + Random random=new Random(); + + File outFile = new File(outputDir+ random.nextInt(200) + ".docx"); //导出文件 + + Writer out = null; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile))); + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + try { + t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件 + return outFile.getPath(); + } catch (TemplateException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return "文档生成失败"; + } + + +} diff --git a/src/main/java/com/teaching/backend/utils/test1.java b/src/main/java/com/teaching/backend/utils/test1.java deleted file mode 100644 index 2ab91d5..0000000 --- a/src/main/java/com/teaching/backend/utils/test1.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.teaching.backend.utils; - -/** - * @Author:youhang - * @Date:2024-05-30-18:20 - * @Description: - */ -public class test1 { -} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 458c718..27c1ff9 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,5 +1,5 @@ -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 +aliyun.oss.endpoint=oss-cn-wuhan-lr.aliyuncs.com +aliyun.oss.accessKeyId=LTAI5tFkdu3y5WddxbjgaG2F +aliyun.oss.accessKeySecret=1xUchxUTlmUBoTV5JQIrKsVjSkmsLF +aliyun.oss.bucketName=ceshi132132 diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b2352d3..e98798c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -18,7 +18,6 @@ mybatis: - classpath:dao/*.xml - classpath*:com/**/mapper/*.xml -# 接口文档配置 knife4j: enable: true openapi: @@ -29,14 +28,4 @@ knife4j: api-rule: package api-rule-resources: - com.teaching.backend.controller -# 接口文档配置 -knife4j: - enable: true - openapi: - title: "111" - version: 1.0 - group: - default: - api-rule: package - api-rule-resources: - - com.teaching.backend.controller + diff --git a/src/main/resources/static/hello2.html b/src/main/resources/static/hello2.html index 15350e9..1b285a4 100644 --- a/src/main/resources/static/hello2.html +++ b/src/main/resources/static/hello2.html @@ -48,5 +48,7 @@ + + diff --git a/src/main/resources/static/hello3.html b/src/main/resources/static/hello3.html new file mode 100644 index 0000000..e69de29