MultipartFile 文件下载
时间: 2023-10-12 19:03:51 浏览: 83
spring jar包下载 含multipart file
5星 · 资源好评率100%
您可以使用Spring框架提供的`MultipartFile`来处理文件下载。以下是一个简单的示例代码:
```java
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/files")
public class FileController {
private static final String FILE_STORAGE_PATH = "/path/to/your/file/storage/directory";
@GetMapping
public List<String> getAllFiles() throws IOException {
return Files.walk(Paths.get(FILE_STORAGE_PATH))
.filter(Files::isRegularFile)
.map(Path::toString)
.collect(Collectors.toList());
}
@GetMapping("/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) throws IOException {
Path filePath = Paths.get(FILE_STORAGE_PATH).resolve(filename);
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
} else {
return ResponseEntity.notFound().build(); }
}
}
```
上述示例代码中,`getAllFiles`方法返回文件存储目录下的所有文件列表。`downloadFile`方法用于下载指定的文件,它根据文件名构建文件路径,并将文件作
阅读全文