我有一个上传文件的表单。我的控制器: -
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());
}
}
}
此代码完美上传并将我上传的文件存储在电子硬盘中。但现在我想在将文件保存到目录之前压缩文件。现在,如果我上传images.jpg它上传images.jpg。我想将这个images.jpg保存为(任何名称),但是采用压缩格式。
答案 0 :(得分:0)
import java.io.*;
import java.util.zip.*;
public class Zip {
static final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new
FileOutputStream("c:\\zip\\myfigs.zip");
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File f = new File(".");
String files[] = f.list();
for (int i=0; i<files.length; i++) {
System.out.println("Adding: "+files[i]);
FileInputStream fi = new
FileInputStream(files[i]);
origin = new
BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
您需要使用ZipOutputStream在java中将数据写入zip。这是一个例子:
<int-jms:message-driven-channel-adapter id="jmsInEldm"container="publishmessageListenerContainer"
channel="IncomingELDMChannel"/>
这是教程,展示了如何在java中压缩和解压缩文件 http://www.oracle.com/technetwork/articles/java/compress-1565076.html