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

master
小萌新 6 months ago
parent fa04f59888
commit fc7daeee79
  1. 8
      pom.xml
  2. 116
      src/main/java/com/teaching/backend/controller/CommonController.java
  3. 66
      src/main/java/com/teaching/backend/controller/WordController.java
  4. 2
      src/main/java/com/teaching/backend/mapper/courses/CoursesMapper.java
  5. 9
      src/main/java/com/teaching/backend/service/FileTableService.java
  6. 132
      src/main/java/com/teaching/backend/service/impl/FileTableServiceImpl.java
  7. 68
      src/main/java/com/teaching/backend/utils/AliOssTest.java
  8. 84
      src/main/java/com/teaching/backend/utils/WordUtil.java
  9. 9
      src/main/java/com/teaching/backend/utils/test1.java
  10. 8
      src/main/resources/application.properties
  11. 13
      src/main/resources/application.yml
  12. 2
      src/main/resources/static/hello2.html
  13. 0
      src/main/resources/static/hello3.html

@ -56,6 +56,13 @@
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
@ -78,6 +85,7 @@
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>

@ -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<String> 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<String> 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;
}
}

@ -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<byte[]> 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<String, Object> 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);
}
}

@ -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;
/**
* <p>
@ -11,6 +12,7 @@ import com.teaching.backend.model.entity.courses.Courses;
* @author zjh
* @since 2024-05-30
*/
@Mapper
public interface CoursesMapper extends BaseMapper<Courses> {
}

@ -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<FileTable> {
void updateFile(String courseId, String fileName, String filePath);
void download(String courseId, HttpServletResponse response, String basePath);
}

@ -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<FileTableMapper,FileTable>
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<FileTable> 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<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,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();
}
}
}
}

@ -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");
}
/*
* <p>转换成word<br>
*/
public String createWord(Map<String,Object> 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 "文档生成失败";
}
}

@ -1,9 +0,0 @@
package com.teaching.backend.utils;
/**
* @Author:youhang
* @Date:2024-05-30-18:20
* @Description:
*/
public class test1 {
}

@ -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

@ -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

@ -48,5 +48,7 @@
</script>
</body>
</html>

Loading…
Cancel
Save