SpringBoot 文件上传与下载


pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vivi</title>
</head>
<body>
<h1>hello Vivi</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

FileUploadController.java

import org.springframework.web.multipart.MultipartFile;

@PostMapping("upload")
@ResponseBody
// MultipartFile 变量名要与 form 表单中的的 type="file" name="file" name 属性名一致
public void upload(MultipartFile file, HttpServletRequest request) throws IOException {
    System.out.println(file.getOriginalFilename()); // 文件名
    System.out.println(file.getContentType()); // 文件类型
    System.out.println(file.getSize()); // 文件大小

    System.out.println(file.getInputStream()); // 获得文件输入流

    // 获得web应用中 files文件夹的绝对路径
    String realPath = request.getServletContext().getRealPath("/files");
    System.out.println(realPath);
    File newFile = new File(realPath);
    // 如果文件夹不存在、则新建
    if (!newFile.exists()) newFile.mkdirs();

    // 上传
    file.transferTo(new File(newFile, file.getOriginalFilename()));
}

文件上传优化

@PostMapping("upload")
@ResponseBody
public void upload(MultipartFile file) throws IOException {
    // 获得 classpath 的绝对路径
    String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
    System.out.println(realPath);
    File newFile = new File(realPath);
    // 如果文件夹不存在、则新建
    if (!newFile.exists()) newFile.mkdirs();
    // 上传
    file.transferTo(new File(newFile, file.getOriginalFilename()));
}

动态修改上传文件的位置(最终)

application.properties

# 用来指定服务器端文件大小的限制
spring.servlet.multipart.max-file-size=300MB

# 用来指定客户端文件大小的限制
spring.servlet.multipart.max-request-size=300MB

fileLocation=static/files

FileUploadController.java

// 读取配置文件中的路径 static/files
@Value("${fileLocation}")
private String fileLocation;

@PostMapping("upload")
@ResponseBody
public void upload(MultipartFile file) throws IOException {
    // 获得 classpath 的绝对路径
    String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
    File newFile = new File(realPath);
    // 如果文件夹不存在、则新建
    if (!newFile.exists()) newFile.mkdirs();
     // 上传
    String fileName = date.getTime() +"@" + file.getOriginalFilename();
    file.transferTo(new File(newFile, fileName));
}

文件下载

index.html

<h1>文件下载</h1>
<a href="/download?fileName=axios.png">axios.png</a><br>
<a href="/download?fileName=layui.png">layui.png</a>


@Value("${fileLocation}")
private String fileLocation;

@GetMapping("download")
public void download(String fileName, HttpServletResponse response) throws IOException {
    // 获得待下载文件所在文件夹的绝对路径
    String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
    // 获得文件输入流
    FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
    // 设置响应头、以附件形式打开文件
    response.setHeader("content-disposition", "attachment; fileName=" + fileName);
    ServletOutputStream outputStream = response.getOutputStream();
    int len = 0;
    byte[] data = new byte[1024];
    while ((len = inputStream.read(data)) != -1) {
        outputStream.write(data, 0, len);
    }
    outputStream.close();
    inputStream.close();
}
你好!关于Spring Boot和Vue文件上传下载的问题,我可以为你提供一些解答。 在Spring Boot中,你可以使用Spring MVC的文件上传功能来处理文件上传。首先,你需要在Spring Boot项目中配置一个文件上传的Bean。可以使用`MultipartResolver`接口来实现文件上传功能。下面是一个示例代码: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } } ``` 接下来,你可以创建一个Controller来处理文件上传请求。你可以使用`@RequestParam`注解来接收上传文件。以下是一个简单的上传文件的示例: ```java @RestController public class FileController { @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 // 返回上传成功的消息 return ResponseEntity.ok("文件上传成功!"); } } ``` 在Vue中,你可以使用`axios`库来发送文件上传请求。以下是一个简单的文件上传的示例代码: ```javascript <template> <div> <input type="file" ref="fileInput" @change="uploadFile"> </div> </template> <script> import axios from 'axios'; export default { methods: { uploadFile() { const file = this.$refs.fileInput.files[0]; const formData = new FormData(); formData.append('file', file); axios.post('/upload', formData) .then(response => { // 处理上传成功的逻辑 console.log(response.data); }) .catch(error => { // 处理上传失败的逻辑 console.error(error); }); } } } </script> ``` 至于文件下载,你可以在Spring Boot中创建一个Controller来处理下载请求。你可以使用`ResponseEntity`来返回文件内容和正确的HTTP头。以下是一个简单的文件下载的示例: ```java @RestController public class FileController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile() throws IOException { // 加载文件资源 Resource fileResource = new ClassPathResource("path/to/file.pdf"); // 设置HTTP头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.pdf"); return ResponseEntity.ok() .headers(headers) .body(fileResource); } } ``` 在Vue中,你可以使用`window.open`方法来下载文件。以下是一个简单的文件下载的示例代码: ```javascript <template> <div> <button @click="downloadFile">下载文件</button> </div> </template> <script> export default { methods: { downloadFile() { const downloadURL = '/download'; window.open(downloadURL, '_blank'); } } } </script> ``` 希望以上信息能够帮助到你!如果有任何问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值