您好,登錄后才能下訂單哦!
在Spring Boot中,實現文件上傳和下載非常簡單。我們將分別介紹如何使用Spring Boot處理文件上傳和文件下載。
首先,我們需要在pom.xml文件中添加以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
接下來,創建一個簡單的HTML表單,用于文件上傳:
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>Upload a file</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
現在,我們將在Controller中處理文件上傳請求:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
@RestController
public class FileUploadController {
private static final String UPLOAD_DIR = "uploads/";
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new ResponseEntity<>("Please select a file to upload.", HttpStatus.BAD_REQUEST);
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
Files.write(path, bytes);
return new ResponseEntity<>("File uploaded successfully: " + file.getOriginalFilename(), HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>("Failed to upload file: " + file.getOriginalFilename(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
這將創建一個名為"uploads"的文件夾,用于存儲上傳的文件。
為了實現文件下載,我們將在Controller中添加一個新的方法:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileDownloadController {
private static final String UPLOAD_DIR = "uploads/";
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
Path path = Paths.get(UPLOAD_DIR + filename);
Resource resource = null;
try {
byte[] bytes = Files.readAllBytes(path);
resource = new ByteArrayResource(bytes);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
現在,您可以通過訪問/download/{filename}
端點來下載文件,其中{filename}
是要下載的文件名。
這就是在Spring Boot中實現文件上傳和下載的方法。請確保在application.properties或application.yml中設置正確的文件上傳目錄。例如,在application.properties中添加以下配置:
file.upload-dir=uploads/
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。