How to compress files uploaded to the server

Preface: As the project is a server api, upload is also a server, so the whole idea is

1, first upload the zip to upload server

2, extract the zip on the upload server.

3, the file upload process decompression on the server (basically json string)

4, the interface call json string to pass through the interface, the operation of the database

One, html

<input id="discoverImg" type="file" name="" class="layui-input">
<input type='button' class="layui-btn layui-btn-primary" onclick="getImg()" value='生成图片'></input>

Two, JS

function getImg(){

var zipUpdate = $("#zipId")[0].files[0];
var formData = new FormData();
formData.append("zipFile",zipUpdate);
uploadZip(formData,callback);

}

function uploadZip(formData, callback){

$.ajax({
url : '/uploadZip',
method : 'POST',
async: false,
processData: false,
contentType:false,
data : formData,
success : function(result) {
callback(result)
}
})

}

function callback(result){
if(result.resultCode==1){
var emojiName = $(".emojiName").val();
// var emojiPath = $(".emojiPath").val();
var emojiProfile = $(".emojiProfile").val();
var emojiEveryName = $(".emojiEveryName").val();
var emojiPath = JSON.stringify(result.data);//将data转化成json String
Common.invoke({
path : '/add',
data : {
'zipName':emojiName,
'zipPath':emojiPath,//json String
'zipProfile': emojiProfile,
'nameStr' :emojiEveryName
},
successMsg : "",
errorMsg : "",
successCb : function(result) {

}
},
errorCb : function(result) {
}
});
}
}

Three, Java,

 // the code is mainly assembled upload the access request and analytical results

the Map getUploadZipPath static public (String Domain, a MultipartFile MultipartFile) { 
String newUrl = null;
the Map = new new mapImags the HashMap ();
the try {
// newline
Final newLine String = "\ R & lt \ n-";
Final boundaryPrefix String = "-" ;
// define the dividing line data
String BOUNDARY = "======== 7d4a6d158c9";
// domain name server of
the uRL of the uRL of new new url = (domain + "/ the Upload / UploadZipServlet");
HttpURLConnection conn = (HttpURLConnection) url. the openConnection ();
// set to POST situation
conn.setRequestMethod ( "POST");
// send a POST request must set the following two lines
conn.setDoOutput (to true);
conn.setDoInput (to true);
conn.setUseCaches (to false);
// parameter setting request header
conn.setRequestProperty ( "Connection", "the Keep-Alive");
conn.setRequestProperty ( "Charsert", "UTF-. 8");
conn.setRequestProperty ( "Content- Type "," multipart / form-the Data; boundary = "+ bOUNDARY);
OutputStream OUT = new new DataOutputStream (conn.getOutputStream ());
// upload files
String fileRealName = multipartFile.getOriginalFilename (); // get the original file name;
the StringBuilder new new SB = the StringBuilder ();
sb.append (boundaryPrefix);
sb.append (BOUNDARY);
sb.append (newLine);
// file parameters, photo free to modify the parameter name
sb.append ( "the Content-Disposition: Data-form; name = \" File \ "; filename = \" "+ fileRealName +" \ "" + newLine);
sb.append ( "the Content-the Type: file application / OCTET - Uninterpreted stream ");
after // End parameter setting requires two head wrap, then the parameter content is
sb.append (newLine);
sb.append (newLine);
// write data header parameter into the output stream
out. Write (sb.toString () the getBytes ().);
// data input stream for reading the file data
DataInputStream in = new new DataInputStream (multipartFile.getInputStream ());
byte [] = BUFFEROUT new new byte [1024];
int = 0 bytes;
// 1KB each read data, and writes the file data to the output stream
the while {((bytes = in.read (BUFFEROUT)) = -1!)
out.write (BUFFEROUT, 0, bytes) ;
}
// added last wrap
out.write (newLine.getBytes ());
in.close ();
// define the final data dividing line, i.e., - adding together the BOUNDARY -.
byte [] end_data = (+ boundaryPrefix newLine the BOUNDARY + + + boundaryPrefix newLine) .getBytes ();
// write end identification
out.write (end_data);
out.flush ();
the out.close ();
// define BufferedReader in response to reading URL input stream of
the BufferedReader Reader the BufferedReader new new = (the InputStreamReader new new (conn.getInputStream ()));
the JSONObject for resultObj = JSON.parseObject (reader.readLine ());
the JSONObject resultData = resultObj.getJSONObject ( "Data") ;
IF (resultData == null)
the throw new new a ServiceException ( "source file does not exist");
JSONArray imagesData = resultData.getJSONArray("images");
JSONArray imagesDataOthers = resultData.getJSONArray("zip");
List zipImags = Lists.newArrayList();
List zip = Lists.newArrayList();
if (imagesData.size() > 0){
for(int i = 0; i< imagesData.size(); i++){
JSONObject imageData = imagesData.getJSONObject(i);
String newUrlO = imageData.getString("oUrl");
String newUrlT = imageData.getString("tUrl");
System.out.println(" upload new Url =====>"+newUrlO);
System.out.println(" upload new Url =====>"+newUrlT);
newUrl = newUrlO + "," + newUrlT;
zipImags.add (newUrl);
}
mapImags.put ( "imags", zipImags);
}
IF (imagesDataOthers.size ()> 0) {
the JSONObject imageDataOthers = imagesDataOthers.getJSONObject (0);
String newUrlOthers = imageDataOthers.getString ( "oUrl ");
zip.add (newUrlOthers);
mapImags.put (" ZIP ", ZIP);
}

} the catch (exception E) {
System.out.println (" POST request transmission abnormal "+ E);!
e.printStackTrace ();
}
return mapImags;
}
// the following is primarily a uploadZip the servlet, I pass some pictures of zip compression, compression and drawing pictures have also original. The main step is below, essence. . . .
@WebServlet("/upload/UploadZipServlet")
public class UploadZipServlet extends BaseServlet {
private static final long serialVersionUID = 1L;

public UploadZipServlet() {
super();
}

@Override
protected JMessage hander(HttpServletRequest request, HttpServletResponse response) {
long start = System.currentTimeMillis();
DiskFileItemFactory factory = new DiskFileItemFactory(1000 * 1024 * 1024, new File(getSystemConfig().getuTemp()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> multipart = null;

JMessage jMessage = null;
int totalCount = 0;
long userId = 0;
double validTime = 0;
try {
multipart = fileUpload.parseRequest(request);
for (FileItem item : multipart) {
if (item.isFormField()) {
if ("validTime".equals(item.getFieldName())) {
try {
validTime = Double.valueOf(item.getString());
} catch (NumberFormatException e) {
validTime = new Double(-1);
}
}
if ("userId".equals(item.getFieldName())) {
userId = Long.parseLong(item.getString());
}
} else {
if (item.getSize() > 0) {
totalCount++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (null == multipart) {
jMessage = new JMessage(1020101, "表单解析失败");
}
else if (0 == totalCount) {
jMessage = new JMessage(1010101, "缺少上传文件");
}
if (null != jMessage)
return jMessage;
jMessage = defHander(multipart, userId, validTime);

int successCount = jMessage.getIntValue("success");
jMessage.put("total", totalCount);
jMessage.put("failure", totalCount - successCount);
jMessage.put("time", System.currentTimeMillis() - start);

return jMessage;
}

protected JMessage defHander(List<FileItem> multipart, long userId, double validTime) {
JMessage jMessage = null;
int successCount = 0;
String oUrl = null;
String tUrl = null;
List<UploadItem> images = Lists.newArrayList();
List<UploadItem> audios = Lists.newArrayList();
List<UploadItem> videos = Lists.newArrayList();
List<UploadItem> others = Lists.newArrayList();
for (FileItem item : multipart) {
UploadItem uploadItem;
if (item.isFormField() || item.getSize() < 1)
continue;
String oFileName = item.getName();
String formatName = ConfigUtils.getFormatName(oFileName);
String newFileName = ConfigUtils.getName(oFileName);
String fileName;
if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {
fileName = 32 == newFileName.length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);
} else {
fileName = oFileName;
}
/*String fileName = 32 == ConfigUtils.getName(oFileName).length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);*/
FileType fileType = getFileType(formatName);
File[] uploadPath = ConfigUtils.getUploadPath(userId, fileType);
File oFile = new File(uploadPath[0], fileName);
File tFile = new File(uploadPath[1], fileName);
try {
FileUtils.transfer(item.getInputStream(), oFile);
successCount++;
oUrl = getUrl(oFile);
if(ConfigUtils.getSystemConfig().isOsStatus()){
if (oUrl.contains(ConfigUtils.getSystemConfig().getDomain())){
String urlNewName = oUrl.replace(ConfigUtils.getSystemConfig().getDomain(),"");
String oUrlNew = FileOSUtil.uploadFile(oFile,urlNewName);
log("UploadServlet uploadEd OBS Other oUrl"+oUrlNew);
if (oUrlNew != null){
oUrl = oUrlNew;
}
}
}
uploadItem = new UploadItem(oFileName, oUrl,(byte) 1, null);
ResourcesDBUtils.saveFileUrl(1, oUrl, -1);
others.add(uploadItem);
log("UploadServlet uploadEd " + oUrl);
try {
ZipInputStream ZinO=new ZipInputStream(new FileInputStream(oFile.getPath()));
BufferedInputStream BinO=new BufferedInputStream(ZinO);
String ParentO=uploadPath[0].toString(); //输出路径(文件夹目录)
File fout=null;
ZipEntry entryO;
try {
while ((entryO = ZinO.getNextEntry()) != null && !entryO.isDirectory()) {
fout = new File(ParentO, entryO.getName());
if (!fout.exists()) {
(new File(fout.getParent())).mkdirs();
}
FileOutputStream outO = new FileOutputStream(fout);
BufferedOutputStream BoutO = new BufferedOutputStream(outO);
int b;
while ((b = BinO.read()) != -1) {
BoutO.write(b);
}
BoutO.close();
outO.close();
System.out.println(fout + "解压成功");
FileInputStream fileInputStream = new FileInputStream(fout);
MultipartFile multipartFile = new MockMultipartFile(fout.getName(), fout.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
images = uploadImg(images,multipartFile,userId,validTime);
}
BinO.close();
ZinO.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
uploadItem = new UploadItem(oFileName, null, (byte) 0, e.getMessage());
others.add(uploadItem);
}
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("zip", others);
data.put("images", images);
jMessage = new JMessage(1, null, data);
jMessage.put("success", successCount);
return jMessage;

}

protected List<UploadItem> uploadImg(List<UploadItem> images,MultipartFile file, long userId, double validTime) {
String oUrl = null;
String tUrl = null;
String oFileName = file.getName();
String formatName = ConfigUtils.getFormatName(oFileName);
String newFileName = ConfigUtils.getName(oFileName);
String imgName;
if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {
imgName = 32 == newFileName.length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);
} else {
imgName = oFileName;
}
FileType imgType = getFileType(formatName);
File[] uploadImgPath = ConfigUtils.getUploadPath(userId, imgType);
File oFile = new File(uploadImgPath[0], imgName);
File tFile = new File(uploadImgPath[1], imgName);
UploadItem uploadItem;
try {
FileUtils.transfer(file.getInputStream(), oFile, tFile, formatName);
oUrl = getUrl(oFile);
tUrl = getUrl(tFile);
if(ConfigUtils.getSystemConfig().isOsStatus()){
if (oUrl.contains(ConfigUtils.getSystemConfig().getDomain())){
String urlNewName = oUrl.replace(ConfigUtils.getSystemConfig().getDomain(),"");
String oUrlNew = FileOSUtil.uploadFile(oFile,urlNewName);
log("UploadServlet uploadEd OBS oUrl "+oUrlNew);
if (oUrlNew != null){
oUrl = oUrlNew;
}
}
if (tUrl.contains(ConfigUtils.getSystemConfig().getDomain())){
String urlNewName = tUrl.replace(ConfigUtils.getSystemConfig().getDomain(),"");
String urlNew = FileOSUtil.uploadFile(tFile,urlNewName);
log("UploadServlet uploadEd OBS tUrl "+urlNew);
if (urlNew != null){
tUrl = urlNew;
}
}
}
ResourcesDBUtils.saveFileUrl(1, oUrl, validTime);
ResourcesDBUtils.saveFileUrl (. 1, Turl, validTime);
log ( "UploadServlet Uploaded" + oUrl);
log ( "UploadServlet Uploaded" + Turl);
uploadItem = new new UploadItem (oFileName, oUrl, Turl, (byte). 1, null);
the catch} (Exception E) {
e.printStackTrace ();
uploadItem = new new UploadItem (oFileName, null, (byte) 0, e.getMessage ());
}
images.add (uploadItem);
return Images;
}
}

Another class is the interface to the database for processing
first json string will be converted into json object, after that they can resolve the matter. . .
JSONObject json = JSONObject.parseObject(zipPath);
Map map = (Map)json;


 

Guess you like

Origin www.cnblogs.com/echo777/p/11311180.html