我有spring boot(后)和angular7(前)应用程序。我需要上传和下载文件。这是我的后端代码
@Entity
@Table
public class File extends BaseEntity {
private String fileName;
private String fileType;
@Lob
private byte[] data;
我的文件存储库:
public interface FileRepo extends CrudRepository<File, Long> {
}
我的文件服务
@Service
public class FileService {
private FileRepo fileRepo;
public FileService(FileRepo fileRepo) {
this.fileRepo = fileRepo;
}
public File storeFile(MultipartFile file){
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try{
File file1 = new File(fileName, file.getContentType(),file.getBytes());
return fileRepo.save(file1);
} catch (IOException io){
throw new FileStorageException("" + fileName + ". !", io);
}
}
}
和我的控制器,在那里我只有两种方法可以通过id上传和下载:
@CrossOrigin(origins = "*", maxAge = 3_600)
@RestController
@RequestMapping(value = "/file")
public class FileController {
private static final Logger log = LogManager.getLogger(FileController.class);
private FileService fileService;
private FileRepo fileRepo;
@Autowired
public FileController(FileService fileService,FileRepo fileRepo){
this.fileRepo = fileRepo;
this.fileService = fileService;
}
@PostMapping("/upload")
public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) {
try {
// fileService.storeFile(file);
return ResponseEntity.ok(fileService.storeFile(file));
} catch (Exception e) {
throw new FileStorageException("", e);
}
}
@RequestMapping(value = "/get/{id}")
public ResponseEntity<?> get(@PathVariable("id") long id) {
try {
File file = fileRepo.findById(id).orElseThrow(() -> new CustomException(String.format("", id)));
// return ResponseEntity.ok().contentType(MediaType.parseMediaType(file.getFileType())).header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + file.getFileName() + "\"")
// .body(new ByteArrayResource(file.getData()));
return ResponseEntity.ok(file);
} catch (CustomException e) {
log.error(e.getMessage());
return ResponseEntity.badRequest().body(e.getMessage());
}
}
}
如何在下载中将正确的格式发送到angular。 我认为XD上传作品
答案 0 :(得分:0)
您可以使用apache commons的FileUtils来实现。构造所需的网址并执行以下代码:
import org.apache.commons.io.FileUtils; //import
URL url = getClass().getResource(filePath);
File file = new File(url.getPath());
if (file.exists()) file.delete();
try {
FileUtils.copyURLToFile(new URL(downloadLink), file, 10000, 10000);
} catch (IOException e) {
e.printStackTrace();
}
依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
您可以根据需要更改以上代码。就我而言,我从网址下载了一个csv文件。