Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.FileDAO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class PutFileController {
@Value("${path_prefix}")
private String pathPrefix;
@Autowired
private FileDAO fileDAO;
@Autowired
private HttpServletRequest request;
@PutMapping("/**")
public ResponseEntity<?> putFile(@RequestParam("file") MultipartFile file) throws IOException {
String path = request.getServletPath();
Optional<FileInfo> optFileInfo = fileDAO.getFileInfo(path);
if (optFileInfo.isPresent()) {
try (InputStream in = file.getInputStream()) {
storeFile(optFileInfo.get(), in);
}
return ResponseEntity.ok().build();
} else {
return new ResponseEntity<>("File " + path + " not found", NOT_FOUND);
}
}
private void storeFile(FileInfo fileInfo, InputStream is) throws IOException {
Path path = Path.of(pathPrefix, fileInfo.getOsRelPath());
File file = path.toFile();
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
throw new IllegalStateException("Unable to create parent folder: " + file.getParentFile().getAbsolutePath());
}
}
Files.copy(is, file.toPath());
}
}