Zhli
Zhli

Reputation: 380

Spring Boot upload files and serve them as static resources

Is it possible to use Spring / Spring Boot to support file uploading and serve the uploaded files as static resouces ?

I followed the official tutorial so that my app could handle file uploading, but when I tried to set the storage root directory to the static resources folder, it did not work.

And I do not want to upload the files to another server or AWS S3.

How to use Spring / Spring Boot to support file uploading and serve the uploaded files as static resouces ?

Upvotes: 0

Views: 2227

Answers (2)

John Sparrow
John Sparrow

Reputation: 19

Try something like this:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<Object> uploadFile(MultipartHttpServletRequest request) {

    final String UPLOAD_FOLDER = "C:\\Folder";

    try {
        request.setCharacterEncoding("UTF-8");
        Iterator<String> itr = request.getFileNames();

        while (itr.hasNext()) {
            String uploadedFile = itr.next();
            MultipartFile file = request.getFile(uploadedFile);
            String mimeType = file.getContentType();
            String filename = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            long size = file.getSize();

            FileUpload newFile = new FileUpload(filename, bytes, mimeType, size);

            String uploadedFileLocation = UPLOAD_FOLDER + newFile.getFilename();

            saveToFile(file.getInputStream(), uploadedFileLocation);

        }
    } catch (Exception e) {
        return new ResponseEntity<>("{INTERNAL_SERVER_ERROR}", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>("Message or Object", HttpStatus.OK);
}

}

private void saveToFile(InputStream inStream, String target) throws IOException {
    OutputStream out = null;
    int read = 0;
    byte[] bytes = new byte[1024];
    out = new FileOutputStream(new File(target));
    while ((read = inStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    out.flush();
    out.close();
}

}

Upvotes: 1

DaShaun
DaShaun

Reputation: 3880

I'm making some assumptions about your environment, but how about this:

Write the files to "somedirectory" then add a @Controller/@RestController that looks for those files and returns them.

@RestController
public class UploadedFilesController {

  @ResponseMapping(value = "grabUploadedFile/{uploadedFileName}",method = RequestMethod.GET)
public ResponseEntity<File> getFile(@PathVariable String uploadedFileName){
  try{
    File toReturn = new File("somedirectory/" + uploadedFileName);
    ResponseEntity<File> r = new ResponseEntity(toReturn, HttpStatus.OK);
  }catch(Exception e){
    return new ResponseEntity(null, HttpStatus.NOT_FOUND);
  }
} 

Upvotes: 0

Related Questions