Java实现文件上传下载

文件上传方法:
1. 该方法用于处理文件上传请求。
2. 检查上传的文件是否为空,如果为空则返回错误消息"文件不能为空"。
3. 如果文件不为空,生成新的文件名,包含UUID作为前缀,保留原文件后缀。
4. 构建目标文件路径,确保目录存在,如果不存在则创建。
5. 将上传的文件复制到目标路径,如果目标文件已经存在,则替换掉它。
6. 方法中可添加其他文件处理逻辑,例如保存到数据库等。
7. 返回响应实体,包含上传结果的消息。

文件下载方法:
1. 该方法用于处理文件下载请求。
2. 根据文件在数据库中的唯一标识(id),获取文件的相关信息,包括文件路径和文件名称。
3. 检查文件是否存在,如果不存在或者不是有效文件,则返回错误消息"文件不存在或者不是一个有效的文件"。
4. 设置强制下载的响应头,包括 `Content-Disposition` 等信息。
5. 使用 try-with-resources 保证文件输入流的关闭。
6. 将文件内容写入响应输出流,实现文件下载。
7. 记录下载操作的日志。
8. 返回响应实体,包含下载结果的消息。
 

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 文件上传、下载工具类
 *
 * @author Gurucyy
 */
@RestController
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    private AttachmentService attachmentService;

    // 读取配置文件中设置的文件存储路径
    @Value(value = "${java.file.path}")
    private String uploadPath;

    /**
     * 文件上传方法
     *
     * @param file 待上传文件
     * @return ResponseEntity 包含上传结果的响应实体
     */
    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
        // 处理文件上传逻辑
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();

                // 提取文件后缀
                String fileExtension = "";
                if (fileName != null && fileName.lastIndexOf(".") != -1) {
                    fileExtension = fileName.substring(fileName.lastIndexOf("."));
                }

                // 生成新的文件名,使用UUID作为前缀,保留原文件后缀
                String newFileName = UUID.randomUUID() + fileExtension;

                // 构建目标文件路径
                File targetFile = new File(uploadPath, newFileName);

                // 确保目录存在,如果不存在则创建
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }

                // 将上传的文件复制到目标路径
                Files.copy(
                        file.getInputStream(),      // 获取上传文件的输入流
                        targetFile.toPath(),        // 目标文件的路径
                        StandardCopyOption.REPLACE_EXISTING  // 如果目标文件已经存在,替换掉它
                );

                // 在这里可以添加文件处理逻辑,比如保存到数据库等

                return ResponseEntity.ok("文件上传成功: " + newFileName);
            } catch (IOException e) {
                return ResponseEntity.badRequest().body("文件上传失败");
            }
        } else {
            return ResponseEntity.badRequest().body("文件不能为空");
        }
    }

    
    /**
     * 文件下载方法
     *
     * @param id       文件在数据库中的唯一标识
     * @param response HTTP响应对象,用于设置下载相关的头信息
     * @return ResponseEntity 包含下载结果的响应实体
     */
    @GetMapping("/download")
    public ResponseEntity downloadFile(@RequestParam("id") Integer id, HttpServletResponse response) {
        try {
            // 常规开发中,文件保存位置通过数据库表进行存储,假设该表对应的实体类对象为Attachment,我们通过id获取对象、文件路径、文件名称等信息
            Attachment attachment = attachmentService.getById(id);    // 获取文件存储对象的实体类
            if (attachment == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在");
            }
            String filePath = attachment.getFilePath();  // 获取文件存储路径
            String fileName = attachment.getName();      // 获取文件名称

            File file = new File(filePath + File.separator + fileName);

            if (!file.exists() || !file.isFile()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在或者不是一个有效的文件");
            }

            // 设置强制下载不打开
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 使用try-with-resources确保资源关闭
            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                // 将文件内容写入响应输出流
                IOUtils.copy(fileInputStream, response.getOutputStream());
            }

            // 记录下载操作的日志
            logger.info("文件下载成功,文件名:{}", fileName);

            return ResponseEntity.ok("下载成功");
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body("参数格式错误");
        } catch (Exception e) {
            logger.error("文件下载失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("下载失败");
        }
    }
}

你可能感兴趣的:(java,开发语言)