21xrx.com
2025-03-23 00:57:15 Sunday
文章检索 我的文章 写文章
Java后端开发
2023-06-10 15:57:47 深夜i     26     0
Java 文件上传 后端开发

最近在开发一个项目,有一个需求就是要实现文件上传功能,我们使用的是Java语言进行开发。

首先,在前端我们需要一个表单来实现文件上传,代码如下:

在这段代码中,我们指定了上传文件的路径为`/upload`,提交方式为`POST`,以及表单的`enctype`为`multipart/form-data`。

接下来,在后端我们需要一个处理文件上传的接口,代码如下:

@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
  storageService.store(file);
  redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
  return "redirect:/";
}

在这段代码中,我们使用了`@RequestParam`注解来获取上传的文件,并且使用`MultipartFile`来表示上传的文件。然后我们使用`storageService`来存储文件,并且在上传成功之后返回一个重定向的页面。

除了上传文件的处理,我们还需要一个存储文件的Service实现,代码如下:

@Service
public class FileSystemStorageService implements StorageService {
  private final Path rootLocation;
  @Autowired
  public FileSystemStorageService(StorageProperties properties) {
    this.rootLocation = Paths.get(properties.getLocation());
  }
  @Override
  public void store(MultipartFile file) {
    try {
      if (file.isEmpty()) {
        throw new StorageException("Failed to store empty file.");
      }
      Path destinationFile = this.rootLocation.resolve(
          Paths.get(file.getOriginalFilename()))
          .normalize().toAbsolutePath();
      if (!destinationFile.getParent().equals(this.rootLocation.toAbsolutePath())) {
        // This is a security check
        throw new StorageException("Cannot store file outside current directory.");
      }
      try (InputStream inputStream = file.getInputStream()) {
        Files.copy(inputStream, destinationFile,
            StandardCopyOption.REPLACE_EXISTING);
      }
    }
    catch (IOException e) {
      throw new StorageException("Failed to store file.", e);
    }
  }
}

在这段代码中,我们使用了`@Service`注解来定义一个服务,其中`store`方法实现了存储上传文件的逻辑。

好啦,现在我们已经实现了Java文件上传功能啦!如果你在开发中也遇到了类似的需求,可以参考一下我的实现方式哦。

三个

  
  

评论区