怎样将压缩⽂件上传到服务器上前⾔:由于项⽬api是⼀台服务器,upload也是⼀台服务器,所以整体思路就是
1,先将zip上传到upload服务器
2,在upload服务器上解压zip。
3,在upload服务器上处理解压的⽂件(基本上都是json string)
4,通过接⼝调⽤将json string传⼊到接⼝中,进⾏数据库的操作
⼀、html
<input id="discoverImg" type="file" name="" class="layui-input">
<input type='button' class="layui-btn layui-btn-primary" onclick="getImg()" value='⽣成图⽚'></input>
⼆、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){
sultCode==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) {
}
});
}
}
三、Java、
//⼀下代码主要是组装访问upload的request和解析结果
public static Map getUploadZipPath(String domain,MultipartFile multipartFile){
String newUrl=null;
Map mapImags = new HashMap();
try {
// 换⾏符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
// 服务器的域名
URL url = new URL(domain+"/upload/UploadZipServlet");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
/
/ 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两⾏
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new OutputStream());
/
/ 上传⽂件
String fileRealName = OriginalFilename();//获得原始⽂件名;
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// ⽂件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileRealName + "\"" + newLine);
sb.append("Content-Type:application/octet-stream");
// 参数头设置完以后需要两个换⾏,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 将参数头的数据写⼊到输出流中inputtypefile不上传文件
out.String().getBytes());
// 数据输⼊流,⽤于读取⽂件数据
DataInputStream in = new InputStream());
byte[] bufferOut = new byte[1024];
int bytes = 0;
// 每次读1KB数据,并且将⽂件数据写⼊到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
/
/ 最后添加换⾏
out.Bytes());
in.close();
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
// 写上结尾标识
out.write(end_data);
out.flush();
out.close();
//          定义BufferedReader输⼊流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStream()));
JSONObject resultObj = JSON.adLine());
JSONObject resultData= JSONObject("data");
if(null == resultData)
throw new ServiceException("源⽂件不存在");
JSONArray imagesData = JSONArray("images");
JSONArray imagesDataOthers = JSONArray("zip");
List zipImags = wArrayList();
List zip = wArrayList();
if (imagesData.size() > 0){
for(int i = 0; i< imagesData.size(); i++){
JSONObject imageData = JSONObject(i);
String newUrlO = String("oUrl");
String newUrlT = String("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){
JSONObject imageDataOthers = JSONObject(0);
String newUrlOthers = String("oUrl");
zip.add(newUrlOthers);
mapImags.put("zip",zip);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return mapImags;
}
//以下主要是⼀个uploadZip的servlet,我传的是⼀些图⽚的zip压缩,⽽且图图⽚有压缩的也有原图。主要的步骤就是在下⾯,精华。。。。@WebServlet("/upload/UploadZipServlet")
public class UploadZipServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
public UploadZipServlet() {
super();
}
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".FieldName())) {
try {
validTime = Double.String());
} catch (NumberFormatException e) {
validTime = new Double(-1);
}
}
if ("userId".FieldName())) {
userId = Long.String());
}
} else {
if (Size() > 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 = IntValue("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 = wArrayList();
List<UploadItem> audios = wArrayList();
List<UploadItem> videos = wArrayList();
List<UploadItem> others = wArrayList();
for (FileItem item : multipart) {
UploadItem uploadItem;
if (item.isFormField() || Size() < 1)
continue;
String oFileName = Name();
String formatName = FormatName(oFileName);
String newFileName = Name(oFileName);
String fileName;
if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {
fileName = 32 == newFileName.length() ? oFileName : ("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);
} else {
fileName = oFileName;
}
/*String fileName = 32 == Name(oFileName).length() ? oFileName : ("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);*/            FileType fileType = getFileType(formatName);
File[] uploadPath = UploadPath(userId, fileType);
File oFile = new File(uploadPath[0], fileName);
File tFile = new File(uploadPath[1], fileName);
try {
successCount++;
oUrl = getUrl(oFile);
SystemConfig().isOsStatus()){
if (SystemConfig().getDomain())){
String urlNewName = SystemConfig().getDomain(),"");
String oUrlNew = FileOSUtil.uploadFile(oFile,urlNewName);
log("UploadServlet uploadEd OBS Other oUrl"+oUrlNew);
if (oUrlNew != null){
}
}
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 Path()));
BufferedInputStream BinO=new BufferedInputStream(ZinO);
String ParentO=uploadPath[0].toString(); //输出路径(⽂件夹⽬录)
File fout=null;
ZipEntry entryO;
try {
while ((entryO = NextEntry()) != null && !entryO.isDirectory()) {
fout = new File(ParentO, Name());
if (!ists()) {
(new Parent())).mkdirs();
}
FileOutputStream outO = new FileOutputStream(fout);
BufferedOutputStream BoutO = new BufferedOutputStream(outO);
int b;
while ((b = ad()) != -1) {
BoutO.write(b);
}
BoutO.close();
outO.close();
System.out.println(fout + "解压成功");
FileInputStream fileInputStream = new FileInputStream(fout);
MultipartFile multipartFile = new Name(), Name(), ContentType.APPLICATION_String(), 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 = Name();
String formatName = FormatName(oFileName);
String newFileName = Name(oFileName);
String imgName;
if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {
imgName = 32 == newFileName.length() ? oFileName : ("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);
} else {
imgName = oFileName;
}
FileType imgType = getFileType(formatName);
File[] uploadImgPath = UploadPath(userId, imgType);
File oFile = new File(uploadImgPath[0], imgName);
File tFile = new File(uploadImgPath[1], imgName);
UploadItem uploadItem;
try {
oUrl = getUrl(oFile);
tUrl = getUrl(tFile);
SystemConfig().isOsStatus()){
if (SystemConfig().getDomain())){
String urlNewName = SystemConfig().getDomain(),"");
String oUrlNew = FileOSUtil.uploadFile(oFile,urlNewName);
log("UploadServlet uploadEd OBS oUrl "+oUrlNew);
if (oUrlNew != null){
oUrl = oUrlNew;
}
}
if (SystemConfig().getDomain())){
String urlNewName = SystemConfig().getDomain(),"");
String urlNew = FileOSUtil.uploadFile(tFile,urlNewName);
log("UploadServlet uploadEd OBS tUrl "+urlNew);
tUrl = urlNew;
}
}
}
ResourcesDBUtils.saveFileUrl(1, oUrl, validTime);
ResourcesDBUtils.saveFileUrl(1, tUrl, validTime);
log("UploadServlet uploadEd " + oUrl);
log("UploadServlet uploadEd " + tUrl);
uploadItem = new UploadItem(oFileName, oUrl, tUrl, (byte) 1, null);
} catch (Exception e) {
e.printStackTrace();
uploadItem = new UploadItem(oFileName, null, (byte) 0, e.getMessage());
}
images.add(uploadItem);
return images;
}
}
还有⼀个类,就是进⾏数据库的处理的接⼝
⾸先将json string转化成json object,之后⾃⼰就可以解析啦。。。
JSONObject json = JSONObject.parseObject(zipPath);
Map map = (Map)json;
进来售后说会出现有的zip可以上传有的不可以,就查了⼀下问题,报错是java.lang.IllegalArgumentException: MALFORMED 所以查了⼀下,说是编码的问题导致解压不成功。
参考⼀个博客 blog.csdn/guying4875/article/details/81034022
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.BitSet;
/**
* @author ⾃动识别⽂件编码格式
*
*/
public class EncodeUtil {
private static Logger logger = Logger(EncodeUtil.class);
private static int BYTE_SIZE = 8;
public static String CODE_UTF8 = "UTF-8";
public static String CODE_UTF8_BOM = "UTF-8_BOM";
public static String CODE_GBK = "GBK";
/**
* 通过⽂件全名称获取编码集名称
*
* @param fullFileName
* @param ignoreBom
* @return
* @throws Exception
*/
public static String getEncode(String fullFileName, boolean ignoreBom) throws Exception {
logger.debug("fullFileName ; {}", fullFileName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fullFileName));
return getEncode(bis, ignoreBom);
}
/**
* 通过⽂件缓存流获取编码集名称,⽂件流必须为未曾
*
* @param bis
* @param ignoreBom 是否忽略utf-8 bom
* @return
* @throws Exception
*/
public static String getEncode(BufferedInputStream bis, boolean ignoreBom) throws Exception {
bis.mark(0);
String encodeType = "未识别";
byte[] head = new byte[3];
if (head[0] == -1 && head[1] == -2) {
encodeType = "UTF-16";
} else if (head[0] == -2 && head[1] == -1) {
encodeType = "Unicode";
} else if (head[0] == -17 && head[1] == -69 && head[2] == -65) { //带BOM
if (ignoreBom) {
encodeType = CODE_UTF8;
} else {
encodeType = CODE_UTF8_BOM;
}
} else if ("Unicode".equals(encodeType)) {
encodeType = "UTF-16";
} else if (isUTF8(bis)) {
encodeType = CODE_UTF8;