Skip to content

Instantly share code, notes, and snippets.

@mloza
Last active December 10, 2020 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloza/933c17518c12d968e6d625d4d81b609e to your computer and use it in GitHub Desktop.
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/
<!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>
@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!";
}
}
@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