Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.avrist.avrist.controller;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.core.io.Resource;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.bind.annotation.CrossOrigin;
- 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.RequestMapping;
- 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;
- import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
- import com.avrist.avrist.models.UploadFile;
- import com.avrist.avrist.service.StorageService;
- import org.apache.commons.io.FilenameUtils;
- @CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = "*")
- @RestController
- @RequestMapping("/api")
- public class UploadController {
- @Autowired
- StorageService storageService;
- List<String> files = new ArrayList<String>();
- @PostMapping("/image")
- public UploadFile handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("url") String url) {
- try {
- String filename = file.getOriginalFilename();
- UUID randomName = UUID.randomUUID();
- String hashName = randomName + "."+FilenameUtils.getExtension(filename);
- files.add(file.getOriginalFilename());
- String Name = "/"+ url + "/" + hashName;
- String fileName = file.getOriginalFilename();
- String fileType = file.getContentType();
- Long fileSize = file.getSize();
- String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
- .path("/api/image/"+ url + "/")
- .path(hashName)
- .toUriString();
- storageService.store(file, url, hashName);
- return new UploadFile(Name, fileDownloadUri, fileType, fileSize);
- } catch (Exception e) {
- return new UploadFile("", "", "", file.getSize());
- }
- }
- @GetMapping("/image/{folder}/{filename:.+}")
- @ResponseBody
- public ResponseEntity<Resource> getFile(@PathVariable String filename, @PathVariable String folder) {
- Resource file = storageService.loadFile(folder, filename);
- return ResponseEntity.ok()
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
- .body(file);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement