批量上传图片到图片服务器

12 篇文章 0 订阅

批量上传图片到图片服务器

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;
	}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的JSch和SCP实现批量上传图片到Linux服务器某个文件夹。以下是一个示例代码: ``` import com.jcraft.jsch.*; import java.io.File; import java.io.FileInputStream; import java.util.Properties; public class UploadImages { public static void main(String[] args) { String localPath = "/path/to/local/folder"; // 本地图片文件夹路径 String remotePath = "/path/to/remote/folder"; // 远程Linux服务器文件夹路径 String username = "your_username"; // Linux服务器用户名 String password = "your_password"; // Linux服务器密码 String host = "your_linux_server_host"; // Linux服务器IP地址 JSch jsch = new JSch(); Session session = null; Channel channel = null; try { session = jsch.getSession(username, host, 22); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; File localFolder = new File(localPath); File[] files = localFolder.listFiles(); for (File file : files) { if (file.isFile()) { FileInputStream fis = new FileInputStream(file); sftp.put(fis, remotePath + "/" + file.getName()); fis.close(); } } sftp.disconnect(); channel.disconnect(); session.disconnect(); System.out.println("上传完成"); } catch (JSchException | SftpException | java.io.IOException e) { e.printStackTrace(); } } } ``` 首先需要引入JSch的jar包,可以从官网下载。然后根据实际情况修改代码中的本地图片文件夹路径、远程Linux服务器文件夹路径、Linux服务器用户名、密码、IP地址等信息。运行代码后,程序会将本地图片文件夹中的所有图片上传到远程Linux服务器的指定文件夹中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值