Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
如何在Java中实现文件上传下载功能_创想鸟

如何在Java中实现文件上传下载功能

实现文件上传需配置multipart参数并用MultipartFile接收,保存至指定目录;2. 文件下载通过UrlResource返回文件流,设置Content-Disposition响应头触发下载;3. 前端使用form表单提交测试,生产环境需增加安全校验。

如何在java中实现文件上传下载功能

在Java中实现文件上传和下载功能,通常用于Web应用中,比如Spring Boot项目。下面分别介绍如何实现文件的上传与下载,使用Spring MVC作为示例框架。

1. 文件上传功能

文件上传需要前端发送multipart/form-data请求,后端接收并保存文件。

步骤说明:

确保依赖中包含对文件上传的支持(Spring Boot默认支持)。配置最大文件大小等参数。编写控制器接收上传请求。

application.yml 配置:

立即学习“Java免费学习笔记(深入)”;

spring:  servlet:    multipart:      max-file-size: 10MB      max-request-size: 10MB

Controller 示例代码:

ViiTor实时翻译 ViiTor实时翻译

AI实时多语言翻译专家!强大的语音识别、AR翻译功能。

ViiTor实时翻译 116 查看详情 ViiTor实时翻译

import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@RestControllerpublic class FileUploadController {    private final String UPLOAD_DIR = "uploads/";    @PostMapping("/upload")    public String uploadFile(@RequestParam("file") MultipartFile file) {        if (file.isEmpty()) {            return "请选择文件";        }        try {            // 创建上传目录            Path dirPath = Paths.get(UPLOAD_DIR);            if (!Files.exists(dirPath)) {                Files.createDirectories(dirPath);            }            // 保存文件            byte[] bytes = file.getBytes();            Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());            Files.write(filePath, bytes);            return "文件上传成功: " + file.getOriginalFilename();        } catch (IOException e) {            return "上传失败: " + e.getMessage();        }    }}

2. 文件下载功能

文件下载通过返回Resource和设置响应头,让浏览器触发下载动作。

实现要点:

根据文件名查找服务器上的文件。使用Resource包装文件。设置Content-Disposition响应头。

Controller 示例代码:

import org.springframework.core.io.Resource;import org.springframework.core.io.UrlResource;import org.springframework.http.HttpHeaders;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import java.net.MalformedURLException;import java.nio.file.Path;import java.nio.file.Paths;@GetMapping("/download/{filename}")public ResponseEntity downloadFile(@PathVariable String filename) {    try {        // 构建文件路径        Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();        Resource resource = new UrlResource(filePath.toUri());        if (resource.exists()) {            return ResponseEntity.ok()                    .header(HttpHeaders.CONTENT_DISPOSITION,                            "attachment; filename="" + resource.getFilename() + """)                    .body(resource);        } else {            return ResponseEntity.notFound().build();        }    } catch (MalformedURLException e) {        return ResponseEntity.badRequest().build();    }}

3. 前端简单测试表单

可用以下HTML测试上传功能:

“`html下载 test.pdf“`

基本上就这些。只要配置好路径和权限,上传下载就能正常运行。注意生产环境要加文件类型校验、防重命名、权限控制等安全措施。不复杂但容易忽略细节。

以上就是如何在Java中实现文件上传下载功能的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/286709.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
怎样延长苹果手机电池寿命
上一篇 2025年11月4日 18:47:32
筑牢人工智能安全防火墙
下一篇 2025年11月4日 18:47:39

相关推荐

发表回复

登录后才能评论
关注微信