Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 上传文件,压缩并保存到内存中_Java_Spring Boot - Fatal编程技术网

Java 上传文件,压缩并保存到内存中

Java 上传文件,压缩并保存到内存中,java,spring-boot,Java,Spring Boot,我有一个上传文件的表格。我的控制器:- public class ConsentController { @Autowired private ConsentRepository consentRepository; private static String UPLOADED_FOLDER = "E://java//files//"; //this directory is used to save the uploaded file public String filepath; @Requ

我有一个上传文件的表格。我的控制器:-

public class ConsentController {
@Autowired
private ConsentRepository consentRepository;
private static String UPLOADED_FOLDER = "E://java//files//"; //this directory is used to save the uploaded file
public String filepath;
@RequestMapping(value="/addconsent",headers=("content-type=multipart/*"),method = RequestMethod.POST)
public String addConsent(@RequestParam("consentstatus") String consentStatus,
                         @RequestParam("file")MultipartFile file,
                         @RequestParam("pid")Participants pid,
                         @RequestParam("participantsid") long participantsid,
                         @RequestParam("userid")User userid,
                         @RequestParam("consentid") long consentid
                         ){
  if(consentRepository.findByParticipants(pid)==null){
      if(file.isEmpty()) {
          Consent consent = new Consent(consentStatus,"null",userid,pid);
          consentRepository.save(consent);
      }
      else{
          try {

              // Get the file and save it somewhere
              byte[] bytes = file.getBytes();
              Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
              Files.write(path, bytes);


              //get the path of the saved filed
              String filename = file.getOriginalFilename();
              String filepath = Paths.get(UPLOADED_FOLDER, filename).toString();
              this.filepath=filepath;
              Consent consent=new Consent(consentStatus,this.filepath,userid,pid);
              consentRepository.save(consent);
          }catch (Exception ex){
              System.out.println("Error"+ex.getMessage());
          }
      }
  }
这段代码完美地上传了我上传的文件并将其存储在e-drive中。但现在我想先压缩文件,然后再将其保存到目录中。现在如果我上传images.jpg,它会上传images.jpg。我希望将images.jpg另存为(任何名称),但采用压缩格式。

这里是来自

import java.io.*;
导入java.util.zip.*;
公共类邮政编码{
静态最终整数缓冲区=2048;
公共静态void main(字符串argv[]){
试一试{
BufferedInputStream原点=null;
FileOutputStream dest=新建
FileOutputStream(“c:\\zip\\myfigs.zip”);
ZipOutputStream out=新ZipOutputStream(新
缓冲输出流(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
字节数据[]=新字节[缓冲区];
//从当前目录获取文件列表
文件f=新文件(“.”);
字符串文件[]=f.list();

对于(int i=0;i,您需要使用ZipoutStream在java中将数据写入zip。以下是一个示例:

public static File zip(List<File> files, String filename) {
    File zipfile = new File(filename);
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
    try {
        // create the ZIP file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        // compress the files
        for(int i=0; i<files.size(); i++) {
            FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
            // add ZIP entry to output stream
            out.putNextEntry(new ZipEntry(files.get(i).getName()));
            // transfer bytes from the file to the ZIP file
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // complete the entry
            out.closeEntry();
            in.close();
        }
        // complete the ZIP file
        out.close();
        return zipfile;
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
    return null;
}
公共静态文件zip(列表文件、字符串文件名){
File zipfile=新文件(文件名);
//创建用于读取文件的缓冲区
字节[]buf=新字节[1024];
试一试{
//创建ZIP文件
ZipOutputStream out=newzipoutpstream(newfileoutputstream(zipfile));
//压缩文件
对于(int i=0;i 0){
out.write(buf,0,len);
}
//完成条目
out.closeEntry();
in.close();
}
//完成ZIP文件
out.close();
返回zipfile;
}捕获(IOEX异常){
System.err.println(例如getMessage());
}
返回null;
}
下面的教程演示了如何在java中压缩和解压缩文件

就这么做吧-
public static File zip(List<File> files, String filename) {
    File zipfile = new File(filename);
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
    try {
        // create the ZIP file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        // compress the files
        for(int i=0; i<files.size(); i++) {
            FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
            // add ZIP entry to output stream
            out.putNextEntry(new ZipEntry(files.get(i).getName()));
            // transfer bytes from the file to the ZIP file
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // complete the entry
            out.closeEntry();
            in.close();
        }
        // complete the ZIP file
        out.close();
        return zipfile;
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
    return null;
}