Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
try {
File oFile = new File("uploads/" + file.getOriginalFilename());
OutputStream os = new FileOutputStream(oFile);
InputStream inputStream = file.getInputStream();
IOUtils.copy(inputStream, os); // 4
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return "Wystąpił błąd podczas przesyłania pliku: " + e.getMessage();
}
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
You can’t perform that action at this time.