基于Java 实现模板的上传下载功能代码
时间: 2024-01-08 17:03:05 浏览: 113
下面是基于Java实现模板上传下载功能的代码示例:
上传模板:
```java
@PostMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败!" + e.getMessage();
}
}
```
下载模板:
```java
@GetMapping("/download/{fileName:.+}")
@ResponseBody
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
Resource resource = null;
try {
Path file = Paths.get(UPLOAD_FOLDER + fileName);
resource = new UrlResource(file.toUri());
if (resource.exists() && resource.isReadable()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return ResponseEntity.notFound().build();
}
```
其中,`UPLOAD_FOLDER`是指定上传文件存储的目录。需要在Spring Boot应用程序的配置文件中指定该目录,如下所示:
```
# 指定上传文件存储的目录
upload.folder = /path/to/upload/folder/
```
在应用程序中,可以使用`@Value`注解来获取该配置参数的值,如下所示:
```java
@Value("${upload.folder}")
private String UPLOAD_FOLDER;
```
通过以上代码实现,即可实现基于Java的模板上传下载功能。
阅读全文