Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.liferon.boot2demo;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.MalformedURLException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.nio.file.StandardCopyOption;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import org.springframework.core.io.Resource;
- import org.springframework.core.io.UrlResource;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.ResponseEntity;
- import org.springframework.util.StringUtils;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.multipart.MultipartFile;
- /**
- *
- * @author olanrewaju.ebenezer
- */
- @RestController
- public class UploadController {
- private final String uploadFolder = "uploads";
- private final Path rootLocation;
- public UploadController() throws IOException {
- rootLocation = Paths.get(uploadFolder);
- if (Files.notExists(rootLocation)) {
- try {
- Files.createDirectories(rootLocation);
- } catch (IOException ex) {
- System.err.println("IOException: " + ex.getMessage());
- throw ex;
- //Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- @GetMapping("/pictures/{filename:.+}")
- @ResponseBody
- public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
- Path path = rootLocation.resolve(filename);
- Resource file = null;
- try {
- file = new UrlResource(path.toUri());
- } catch (MalformedURLException ex) {
- Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
- }
- return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
- "attachment; filename=\"" + file.getFilename() + "\"").body(file);
- }
- @PostMapping("/api/upload")
- public ResponseEntity<?> handleFileUpload(@RequestParam("picture") MultipartFile picture) {
- String filename = StringUtils.cleanPath(picture.getOriginalFilename());
- try (InputStream inputStream = picture.getInputStream()) {
- Files.copy(inputStream, this.rootLocation.resolve(filename),
- StandardCopyOption.REPLACE_EXISTING);
- } catch (IOException ex) {
- Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
- }
- return ResponseEntity.ok("File uploaded successfully");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment