简体   繁体   中英

Not able to convert Image(byte array)from table to Multipart file Spring mvc

Issue:Not able to convert bytes to multipart file, I used custom multipart file to wrap bytes, name, size,content type. Image is store in destination part but it is not displayed in the front end. No error in logs.Can some one help me to fix this.

Custom Multipart file.

    public class BASE64DecodedMultipartFile implements MultipartFile {
    private final byte[] imgContent;
    private String contentType;
    private String originalFilename;
    private String destPath = System.getProperty("java.io.tmpdir");

    private FileOutputStream fileOutputStream;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    private File file;
    private long size;

    public BASE64DecodedMultipartFile(byte[] imgContent, String contentType,String originalFilename,String path,long size) {
        this.imgContent = imgContent;
        this.contentType=contentType;
        this.originalFilename=originalFilename;
        file = new File(destPath + originalFilename);
        this.size=size;
    }
    @Override
    public String getName() {
        return "picture";
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public long getSize() {
        return size;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(imgContent);
    }
}

Used custom Multipart file as below.

 BASE64DecodedMultipartFile bASE64DecodedMultipartFile=new BASE64DecodedMultipartFile(imgbytes,"image/png","pleasure image 1.png",path,527110);
 
        bASE64DecodedMultipartFile.transferTo(bASE64DecodedMultipartFile.getFile());

//Stored in the form which is sent as view. form.setPicture(bASE64DecodedMultipartFile);

JSP Page:

<div class="col-sm-9">

I am not getting image content in UI: enter image description here

Recently I was trying to convert from bytearray to multipart, and i was able to achieve this and i don't know if this approach is good or not(open for suggestions)

  1. Pojo class to get properties files

     @ConfigurationProperties(prefix = "file") public class FileStorageProperties { private String uploadDir; public String getUploadDir() { return uploadDir; } public void setUploadDir(String uploadDir) { this.uploadDir = uploadDir; } }
  2. Controller

    @RestController public class FileController {

     private static final Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private FileStorageService fileStorageService; @PostMapping("/uploadFile") public UploadFileResponse uploadFile(@RequestParam(value = "image") base64Str: String, fileName: String?) { String fileName = fileStorageService.storeFile(Base64DecodedMultipartFile(Base64.getMimeDecoder().decode(base64Str),fileName)); String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/downloadFile/").path(fileName).toUriString(); return new UploadFileResponse(fileName, fileDownloadUri, file.getContentType(), file.getSize()); } @PostMapping("/uploadMultipleFiles") public List<UploadFileResponse> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) { return Arrays.asList(files).stream().map(file -> uploadFile(file)).collect(Collectors.toList()); } @GetMapping("/downloadFile/{fileName:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) { // Load file as Resource Resource resource = fileStorageService.loadFileAsResource(fileName); // Try to determine file's content type String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException ex) { logger.info("Could not determine file type."); } // Fallback to the default content type if type could not be determined if(contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").body(resource); }

    }

  3. Service class

     @Service public class FileStorageService { private final Path fileStorageLocation; @Autowired public FileStorageService(FileStorageProperties fileStorageProperties) { this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize(); try { Files.createDirectories(this.fileStorageLocation); } catch (Exception ex) { throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex); } } public String storeFile(MultipartFile file) { // Normalize file name String fileName = StringUtils.cleanPath(file.getOriginalFilename()); try { // Check if the file's name contains invalid characters if(fileName.contains("..")) { throw new FileStorageException("Sorry; Filename contains invalid path sequence " + fileName). } // Copy file to the target location (Replacing existing file with the same name) Path targetLocation = this.fileStorageLocation;resolve(fileName). Files.copy(file,getInputStream(), targetLocation. StandardCopyOption;REPLACE_EXISTING); return fileName. } catch (IOException ex) { throw new FileStorageException("Could not store file " + fileName + ", Please try again;". ex). } } public Resource loadFileAsResource(String fileName) { try { Path filePath = this.fileStorageLocation;resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if(resource;exists()) { return resource, } else { throw new MyFileNotFoundException("File not found " + fileName); } } catch (MalformedURLException ex) { throw new MyFileNotFoundException("File not found " + fileName, ex); } } }
     MultipartFile implemetation 
    
class Base64DecodedMultipartFile implements MultipartFile {

    private Byte[] image;
    private String fileName;

    public Base64DecodedMultipartFiles(Byte[] image, String fileName) {
        this.image = image;
        this.fileName = fileName;
    }

    @Override
    public String getName() {
        return "picture";
    }

    @Override
    public String getOriginalFilename() {
        return fileName;
    }

    @Override
    public String getContentType() {
        return MediaType.MULTIPART_FORM_DATA_VALUE;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public long getSize() {
        return image.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return image;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(image);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
       new FileOutputStream(file).write(image);
    }
}

In multpartFile implementation you can customize based on you requirement, and for file upload you can refer this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM