批量上传图片到图片服务器
package com.goldgrid.util.batchpic;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.goldgrid.Constants;
import com.goldgrid.filestor.FileStor;
import com.goldgrid.mobile.dao.AreaDAO;
import com.goldgrid.mobile.dao.OrderLogDao;
import com.goldgrid.mobile.image.dao.ImageDao;
import com.goldgrid.mobile.image.entity.Image;
import com.goldgrid.mobile.model.Picture;
import com.goldgrid.mobile.model.PictureLibrary;
import com.goldgrid.web.core.util.FileUtils;
import com.goldgrid.web.core.util.GoldGridUtil;
import com.goldgrid.web.core.util.PathUrlUtil;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
/**
* 批量上传图片到服务端
* Servlet implementation class BatchImportPicToServer
*/
public class BatchImportPicToServer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected static Logger logger=Logger.getLogger(BatchImportPicToServer.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
OrderLogDao orderLogDao=new OrderLogDao();
ImageDao imageDao=new ImageDao();
String operatorNum="ahdx";
String importPicPath=this.getServletContext().getRealPath("/importpicture/");
File file=new File(importPicPath);
try {
if(!file.exists()) {
throw new Exception("Can not found file named importpicture!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(file.isDirectory()) {
File[] fileFirstFolder=file.listFiles();
if(fileFirstFolder.length>0) {
for(int i=0;i<fileFirstFolder.length;i++) {
//StringBuffer stringBuffer=new StringBuffer();
//文件夹名为areaCode
String areaCodeFilePath=fileFirstFolder[i].getPath();
String areaCodeFileName=fileFirstFolder[i].getName();
String areaCode=areaCodeFileName;
File areaCodeFolder=new File(areaCodeFilePath);
if(areaCodeFolder.isDirectory()) {
File[] fileSecondFolder = areaCodeFolder.listFiles();
if(fileSecondFolder.length>0) {
for(int j=0;j<fileSecondFolder.length;j++) {
//文件夹名为businessid
String businessFilePath=fileSecondFolder[j].getPath();
String businessFileName=fileSecondFolder[j].getName();
String businessid=businessFileName;
PictureLibrary pictureLibrary=new PictureLibrary();
Picture picture=new Picture();
AreaDAO areaDao=AreaDAO.getInstance();
try {
pictureLibrary=areaDao.selectPicFromPL(businessid, areaCode);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(null==pictureLibrary || "".equals(pictureLibrary)) {
logger.info("在picture_library表中未找到areaCode为"+areaCode+"、businessid为"+businessid+"的订单记录,无法导入!");
continue;
}
String plid=pictureLibrary.getPlId();
try {
picture=areaDao.selectPsByPlid(plid);
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if(picture == null) {
File businessFolder=new File(businessFilePath);
ArrayList<String> picTypeList=new ArrayList<String>();
File[] pictureFiles=businessFolder.listFiles();
String cpid=UUID.randomUUID().toString();
String pid=UUID.randomUUID().toString();
if(pictureFiles.length>0) {
for(int k=0;k<pictureFiles.length;k++) {
String picturePath=pictureFiles[k].getPath();
String pictureName=pictureFiles[k].getName();
String pictureType=pictureName.substring(0,pictureName.indexOf("."));
try {
Boolean tempResult=areaDao.insertImportTemp(businessid, operatorNum, pictureName, pictureType);
if(tempResult==false) {
logger.info("导入areaCode为"+areaCode+"、businessid为"+businessid+"pictureType为"+pictureType+"的订单到t_picturetemp表失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String name = UUID.randomUUID()+".jpg";
String tid = UUID.randomUUID().toString();
StringBuffer stringBuffer1 = new StringBuffer();
String tmpRobotPicsPath = PathUrlUtil.getRealTempFilePath(request,
stringBuffer1, "tmpPro", ".pdf");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = formatter.format(System.currentTimeMillis());
String minFolderName = GoldGridUtil.getSystemDateMin(formatter.parse(date));
//年月文件夹名
String YearMonFolderName = GoldGridUtil.getSystemDateYearMonth(formatter.parse(date));
//日文件夹名
String DayFolderName = GoldGridUtil.getSystemDateDay(formatter.parse(date));
//小时文件夹名
String hourFolderName = GoldGridUtil.getSystemDateHour(formatter.parse(date));
String filePath = tmpRobotPicsPath.substring(0,
tmpRobotPicsPath.lastIndexOf("/"))+"/image/";
// appendPath格式为 201805/24/18/30-34/
String appendPath = YearMonFolderName +"/"+DayFolderName+"/"+hourFolderName+"/"+minFolderName+"/";
// end
String filePathNew = filePath+appendPath;
if(!new File(filePathNew).exists()){
new File(filePathNew).mkdirs();
}
String loaclPicPath=importPicPath+"/"+areaCode+"/"+businessid+"/"+pictureType+".jpg";
String picServerPath=tid+"_"+pictureType+".jpg";
BatchImportPicToServer.BatchPicUpload(loaclPicPath, picServerPath, areaCode,appendPath);
String imagePath=appendPath+tid+"_"+pictureType+".jpg";
Image image = new Image();
image.setNewpath_por(Constants.FILEUPLOAD_NEWPATH_POR);
image.setSeveruser1(Constants.FILEUPLOAD_SEVERUSER1);
image.setSeverpwd1(Constants.FILEUPLOAD_SEVERPWD1);
image.setSeverip(Constants.FILEUPLOAD_SEVERIP1);
image.setPlid(pid);
image.setBussinessid(businessid);
image.setImagePath(imagePath);
image.setAreacode(areaCode);
image.setType(pictureType);
image.setCpid(cpid);
imageDao.insertImage(image);
Picture eachPic=new Picture();
eachPic.setpTime(new SimpleDateFormat("yyyy--MM--dd HH:mm:ss").format(new Date()));
eachPic.setPid(pid);
eachPic.setPictureType(pictureType);
eachPic.setPictureName(imagePath);
eachPic.setOperateCode(operatorNum);
eachPic.setpBusinessid(businessid);
eachPic.setPcode(areaCode);
eachPic.setPplid(plid);
try {
orderLogDao.savePicture(eachPic);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
List<Image> images = null;
String typeImg = "";
try {
images = imageDao.findImage(businessid, areaCode);
for(Image img:images) {
String itype=img.getType();
if("11".equals(itype)) {
itype="7";
}
if("22".equals(itype)) {
itype="8";
}
typeImg=typeImg+itype+",";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String deletion="";
if(typeImg.indexOf("1")==-1 &&typeImg.indexOf("2")!=-1) {
deletion+="1";
}
if(typeImg.indexOf("1")!=-1 &&typeImg.indexOf("2")==-1) {
deletion+="2";
}
if(typeImg.indexOf("1")==-1 &&typeImg.indexOf("2")==-1) {
deletion+="12";
}
if(typeImg.indexOf("7")==-1 &&typeImg.indexOf("8")!=-1) {
deletion+="3";
}
if(typeImg.indexOf("7")!=-1 &&typeImg.indexOf("8")==-1) {
deletion+="4";
}
if(typeImg.indexOf("7")==-1 &&typeImg.indexOf("8")==-1) {
deletion+="34";
}
if(typeImg.indexOf("3")==-1) {
deletion+="6";
}
for(Image imageDeletion:images){
imageDeletion.setDeletion(deletion);
imageDeletion.setAreacode(areaCode);
imageDeletion.setBussinessid(businessid);
imageDao.updateDeletion(imageDeletion);
}
}
}else {
logger.info("在t_picturestorage表中已有areaCode为"+areaCode+"、businessid为"+businessid+"的订单记录,无需重复导入!");
continue;
}
}
}
}
}
}
}
}
public BatchImportPicToServer() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
public static boolean BatchPicUpload(String localPicPath,
String picServerPath,String areaCode,String appendPath) throws Exception {
//separator相当于双斜杆://
String separator = System.getProperty("file.separator");
boolean result = false;
String businessFront=localPicPath.substring(0,localPicPath.lastIndexOf("/"));
String areaCodeFront=businessFront.substring(0,businessFront.lastIndexOf("/"));
String importPicFront=areaCodeFront.substring(0,areaCodeFront.lastIndexOf("/"));
String importPicture=importPicFront.substring(importPicFront.length()-13,importPicFront.length());
FileStor fileStor = new FileStor();
fileStor.setUserName(Constants.FILEUPLOAD_SEVERUSER1);
fileStor.setPassWord(Constants.FILEUPLOAD_SEVERPWD1);
fileStor.setServerIp(Constants.FILEUPLOAD_SEVERIP1);
fileStor.setRootDir(Constants.FILEUPLOAD_NEWPATH_POR);
String remoteUrl = null;
String remoteDir = null;
if("importpicture".equals(importPicture)) {
remoteUrl = "smb://" + fileStor.getUserName() + ":"
+ fileStor.getPassWord() + "@" + fileStor.getServerIp() + "/"
+ fileStor.getRootDir() + "/image/" + areaCode +"/" +appendPath +picServerPath;
remoteDir = remoteUrl.substring(0, remoteUrl.lastIndexOf("/"));
}else {
throw new Exception("图片存放地址有误!");
}
SmbFile fDir;
SmbFile f;
FileInputStream in = null;
SmbFileOutputStream out = null;
try {
f = new SmbFile(remoteUrl);
fDir = new SmbFile(remoteDir);
if (!fDir.exists()) {
fDir.mkdirs();
}
if (!f.exists()) {
in = new FileInputStream(localPicPath);
out = new SmbFileOutputStream(f);
byte[] b = new byte[8192];
int n, tot = 0;
while ((n = in.read(b)) > 0) {
out.write(b, 0, n);
tot += n;
}
result = true;
} else {
result = true;
}
} catch (Exception e) {
System.out.println("Smb服务上传文件异常!上传文件路径:" + remoteUrl + " 异常:"+ e);
} finally {
try {
if (null != in){
in.close();
}
} catch (IOException e) {
System.out.println("关闭流异常!" + e);
}
try {
if (null != out){
out.flush();
out.close();
}
} catch (IOException e) {
System.out.println("关闭流异常!" + e);
}
}
return result;
}
}
public static String getRealTempFilePath(HttpServletRequest request, StringBuffer stringBuffer, String webRootDir, String extType){
String tmpAccessoryDIR = PathUrlUtil.getWebRealRoot(request);
String tmpAccessoryFileName = GoldGridUtil.getSystemDate2() +"-" + UUID.randomUUID().toString().replaceAll("-", "") + extType;
String tmpAccessoryFilePath = tmpAccessoryDIR + webRootDir + "/" + tmpAccessoryFileName;
tmpAccessoryFilePath = tmpAccessoryFilePath.replaceAll("\\\\", "/");
stringBuffer.append(tmpAccessoryFileName);
File file = new File(tmpAccessoryDIR + webRootDir);
if(!file.exists()){
file.mkdirs();
}
return tmpAccessoryFilePath;
}