Last active
December 10, 2020 18:56
-
-
Save mloza/933c17518c12d968e6d625d4d81b609e to your computer and use it in GitHub Desktop.
Kod źródłowy do wpisu o wysyłaniu plików na serwer za pomocą spring boota i javy znajdujący się pod adresem: https://blog.mloza.pl/wysylanie-plikow-na-serwer-przez-spring-boot/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" | |
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>File upload</title> | |
</head> | |
<body> | |
<form action="/upload" method="post" enctype="multipart/form-data"> | |
<input type="file" name="fileupload"/> | |
<button type="submit">Wyślij</button> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Controller | |
public class UploadController { | |
@PostMapping("/upload") | |
@ResponseBody // 1 | |
public String handleFile(@RequestPart(name = "fileupload") MultipartFile file) { // 2 | |
File uploadDirectory = new File("uploads"); | |
uploadDirectory.mkdirs(); // 3 | |
File oFile = new File("uploads/" + file.getOriginalFilename()); | |
try (OutputStream os = new FileOutputStream(oFile); | |
InputStream inputStream = file.getInputStream()) { | |
IOUtils.copy(inputStream, os); // 4 | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return "Wystąpił błąd podczas przesyłania pliku: " + e.getMessage(); | |
} | |
return "ok!"; | |
return "ok!"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@GetMapping("image/{name}") | |
public ResponseEntity showImage(@PathVariable String name) throws IOException { | |
File file = new File("uploads/" + name); | |
if (!file.exists()) { | |
return ResponseEntity.notFound().build(); | |
} | |
return ResponseEntity.ok() | |
.contentType(MediaType.valueOf(URLConnection.guessContentTypeFromName(name))) | |
.body(Files.readAllBytes(file.toPath())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment