Last active
April 8, 2018 02:13
-
-
Save m-x-k/04d5e79bfbbf371ad0bfa477f3660900 to your computer and use it in GitHub Desktop.
Spring boot jpa mongo gridfs example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
spring: | |
data: | |
mongodb: | |
host: localhost | |
port: 27017 | |
database: myfiles | |
multipart: | |
maxFileSize: 32Mb | |
maxRequestSize: 32Mb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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