xxxxxxxxxx
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface FileService {
String saveFile(MultipartFile file) throws IOException;
}
import com.example.demo_file_uploa_2.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
@Service
public class FileServiceImp implements FileService {
Path path;
public FileServiceImp() {
path = Paths.get("src/main/resources/images");
}
@Override
public String saveFile(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
UUID uuid = UUID.randomUUID();
fileName = uuid + fileName;
Path resolvePath = path;
if (!file.isEmpty()) {
resolvePath = path.resolve(fileName);
}
Files.copy(file.getInputStream(), resolvePath, StandardCopyOption.REPLACE_EXISTING);
return fileName;
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FileConfiguration implements WebMvcConfigurer {
String path = "src/main/resources/images/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + path);
}
}
import com.example.demo_file_uploa_2.service.FileService;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/file")
public class FileUploadController {
private final FileService fileService;
public FileUploadController(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(value = "/file-upload", consumes = {"multipart/form-data"})
public String uploadFileToServer(
@RequestParam("file") MultipartFile file
) {
System.out.println(file);
try {
String fileUpload = fileService.saveFile(file);
System.out.println("this is file : " + fileUpload);
return fileUpload;
} catch (Exception e) {
System.out.println("error message : " + e.getMessage());
}
return null;
}
xxxxxxxxxx
// this my reset call
//...... rest cocde
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
Resource file = storageService.load(filename);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file);
}
@PostMapping("/upload")
public ResponseEntity<JSONObject> uploadFile(@RequestParam("file") MultipartFile file, @RequestHeader HttpHeaders headers) {
JSONObject message = new JSONObject();
String email = helpers.GetUserFromToken(headers); //this is my stuff for JWT
System.out.println(file);
String filename = file.getOriginalFilename();
String extension =filename.substring(filename.lastIndexOf(".") + 1);
Long fileSize = file.getSize();
String[] nameArray = new String[]{"jpg", "png", "jpeg"};
List<String> array = new ArrayList<String>(Arrays.asList(nameArray));
if(array.contains(extension.toLowerCase()) && (fileSize/1025 < 500)){ //Validation
try {
String FileName = storageService.save(file); //save in Folder Watch the function blow class named with save method
message.put("status","success");
message.put("msg","Uploaded the file successfully: " + FileName);
userServices.UpdateProfilePic(email,FileName); // save in DATABASE
return ResponseEntity.status(HttpStatus.OK).body(message);
} catch (Exception e) {
message.put("status","error");
message.put("msg","Could not upload the file: " + file.getOriginalFilename() + ". Error: " + e.getMessage());
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
}
}else{
message.put("status","error");
message.put("msg","incorrect file format or file size");
if(!array.contains(extension.toLowerCase())){
message.put("format_allowed","jpg,png,jpeg");
}
if( (fileSize/1025 > 500)){
message.put("file_size","the file Size Should be blow 500kb");
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(message);
}
}
// is my main Storage file which handles everything
package it.XYZ.storage; // change as per your project
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class StorageServiceImp implements StorageService{
private final Path root = Paths.get("uploads");
@Override
public String save(MultipartFile file) {
String newName = "";
try {
// get the file and change with current dateTime
String filename = file.getOriginalFilename();
String extension =filename.substring(filename.lastIndexOf(".") + 1);
newName = String.valueOf(System.currentTimeMillis()).concat("."+extension); // rewrite name of file
// get the file and change with current dateTime
Files.copy(file.getInputStream(), this.root.resolve(newName));
} catch (Exception e) {
if (e instanceof FileAlreadyExistsException) {
throw new RuntimeException("A file of that name already exists.");
}
throw new RuntimeException(e.getMessage());
}
return newName;
}
@Override
public Resource load(String filename) {
try {
Path file = root.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("Could not read the file!");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Error: " + e.getMessage());
}
}
@Override
public void deleteFile(String FileName) {
try {
File existingFile = new File(this.root.resolve(FileName).toUri());
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
}catch (Exception e){
}
}
}
xxxxxxxxxx
import org.springframework.web.multipart.MultipartFile;
1. FileService
import java.io.IOException;
public interface FileService {
String saveFile(MultipartFile file) throws IOException;
}
2. FileServiceImp
import com.example.demo_file_uploa_2.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
@Service
public class FileServiceImp implements FileService {
Path path;
public FileServiceImp() {
path = Paths.get("src/main/resources/images");
}
@Override
public String saveFile(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
UUID uuid = UUID.randomUUID();
fileName = uuid + fileName;
Path resolvePath = path;
if (!file.isEmpty()) {
resolvePath = path.resolve(fileName);
}
Files.copy(file.getInputStream(), resolvePath, StandardCopyOption.REPLACE_EXISTING);
return fileName;
}
}
3. FileConfiguration
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FileConfiguration implements WebMvcConfigurer {
String path = "src/main/resources/images/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + path);
}
}
4. FileUploadController
import com.example.demo_file_uploa_2.service.FileService;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/file")
public class FileUploadController {
private final FileService fileService;
public FileUploadController(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(value = "/file-upload", consumes = {"multipart/form-data"})
public String uploadFileToServer(
@RequestParam("file") MultipartFile file
) {
System.out.println(file);
try {
String fileUpload = fileService.saveFile(file);
System.out.println("this is file : " + fileUpload);
return fileUpload;
} catch (Exception e) {
System.out.println("error message : " + e.getMessage());
}
return null;
}
}
xxxxxxxxxx
//Upload file from Springboot invoking an API end point
//https://www.javacodemonk.com/multipart-file-upload-spring-boot-resttemplate-9f837ffe
private void testUploadFile(Path path) throws IOException {
String fileName = path.getFileName().toString();
byte[] fileContent = FileUtils.readFileToByteArray(path.toFile());
HttpHeaders parts = new HttpHeaders();
parts.setContentType(MediaType.TEXT_PLAIN);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.valueOf("application/pdf"));
headers.setContentDisposition(ContentDisposition.builder("attachment").filename(fileName).build());
headers.setBasicAuth("cdsgsgasdfdse==");
HttpEntity<byte[]> entity = new HttpEntity<>(fileContent, headers);
ResponseEntity<String> response = restTemplate.postForEntity("http://url_for_file_upload_api_endpoint", entity, String.class);
if(response.getStatusCode().is2xxSuccessful()) {
System.out.println("File uploaded = " + response.getBody());
}
}
xxxxxxxxxx
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface FileService {
String saveFile(MultipartFile file) throws IOException;
}
import com.example.demo_file_uploa_2.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
@Service
public class FileServiceImp implements FileService {
Path path;
public FileServiceImp() {
path = Paths.get("src/main/resources/images");
}
@Override
public String saveFile(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
UUID uuid = UUID.randomUUID();
fileName = uuid + fileName;
Path resolvePath = path;
if (!file.isEmpty()) {
resolvePath = path.resolve(fileName);
}
Files.copy(file.getInputStream(), resolvePath, StandardCopyOption.REPLACE_EXISTING);
return fileName;
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FileConfiguration implements WebMvcConfigurer {
String path = "src/main/resources/images/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("file:" + path);
}
}
import com.example.demo_file_uploa_2.service.FileService;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/v1/file")
public class FileUploadController {
private final FileService fileService;
public FileUploadController(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(value = "/file-upload", consumes = {"multipart/form-data"})
public String uploadFileToServer(
@RequestParam("file") MultipartFile file
) {
System.out.println(file);
try {
String fileUpload = fileService.saveFile(file);
System.out.println("this is file : " + fileUpload);
return fileUpload;
} catch (Exception e) {
System.out.println("error message : " + e.getMessage());
}
return null;
}