Skip to content

Instantly share code, notes, and snippets.

@m-x-k
Last active April 8, 2018 02:13
Show Gist options
  • Save m-x-k/04d5e79bfbbf371ad0bfa477f3660900 to your computer and use it in GitHub Desktop.
Save m-x-k/04d5e79bfbbf371ad0bfa477f3660900 to your computer and use it in GitHub Desktop.
Spring boot jpa mongo gridfs example
spring:
data:
mongodb:
host: localhost
port: 27017
database: myfiles
multipart:
maxFileSize: 32Mb
maxRequestSize: 32Mb
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Controller
public class FileUploadController {
@Autowired
private GridFsTemplate gridFsTemplate;
@RequestMapping(method = RequestMethod.POST, value = "/upload")
@ResponseBody
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file,
@RequestParam("filename") String filename) throws IOException {
gridFsTemplate.store(file.getInputStream(), filename);
return new ResponseEntity<>("", HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
@ResponseBody
public ResponseEntity<?> getFile(@PathVariable String filename) {
try {
return ResponseEntity.ok(gridFsTemplate.getResource(filename));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment