H5 MultipartFile上传文件
时间: 2023-12-02 11:42:40 浏览: 34
以下是使用H5的MultipartFile上传文件的示例代码:
```html
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file"/>
<input type="submit" value="Upload"/>
</form>
```
在后端Java代码中,可以使用Spring框架提供的MultipartFile类来处理上传的文件。示例代码如下:
```java
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/";
}
```
在上述代码中,我们首先检查上传的文件是否为空,然后使用getBytes()方法获取文件的字节数组,最后将文件保存到指定的目录中。