【问题标题】:Not able to convert Image(byte array)from table to Multipart file Spring mvc无法将图像(字节数组)从表转换为多部分文件 Spring mvc
【发布时间】:2020-11-17 13:57:26
【问题描述】:

问题:无法将字节转换为多部分文件,我使用自定义多部分文件来包装字节、名称、大小、内容类型。图像存储在目标部分,但不显示在前端。 日志中没有错误。谁能帮我解决这个问题。

自定义多部分文件。

    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);
    }
}

使用自定义的 Multipart 文件如下。

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

//以视图发送的形式存储。 form.setPicture(bASE64DecodedMultipartFile);

JSP 页面:

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

我没有在 UI 中获取图像内容: enter image description here

【问题讨论】:

    标签: javascript java spring-mvc jsp


    【解决方案1】:

    最近我试图从 bytearray 转换为 multipart,我能够实现这一点,但我不知道这种方法是否好(欢迎提出建议)

    1. Pojo 类获取属性文件

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

      @RestController 公共类 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
        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);
        }
    }
    

    在 multpartFile 实现中,您可以根据需要自定义,文件上传可以参考this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-25
      • 2019-05-18
      • 1970-01-01
      • 2011-03-07
      • 2015-08-18
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      相关资源
      最近更新 更多