my java learning

1,首先是html页面(imgTest.jsp)


<span class="htgl_addpro_content_high_content" style="margin-left: 10px;">
<p>
<img id="imgsrc" src="<%=basePath%>images/nopic.gif" width="131" height="180"></p>
<p>
<input type="text" id="imageUrlTmp" name="htglBookInfo.imageName" disabled value="" style="width: 220px; height: 28px; float: left;" class="txt1 isChanged"><input type="hidden" id="imageUrl" name="htglBookInfo.imageName" value="" style="width: 400px; height: 28px; float: left;" class="txt1 isChanged"><input id="chooseImg" type="button" class="darkBtn" value="浏览" style="height: 34px; width: 100px; margin-left: 45px; float: left;" size="10"><!-- <label style="color:red">(*.jpg; *.gif;)</label> --><input type="file" id="fileField1" style="" name="file"><input type="text" style="" value="<%=basePath%>" id="imgPath"><input type="text" style="" id="imgUrlToDb" name="htglBookInfo.imageUrl" value="${htglBookInfo.imageUrl }"></p>
</span>


2,struts配置(struts.xml)

<?xml version="1.0" encoding="UTF-8" ?><struts><!-- <interceptor-stack name="fileUploadStack">
<interceptor-ref name="fileUpload" />
<interceptor-ref name="defaultStack" />
</interceptor-stack> --><constant name="struts.devMode" value="true"></constant><constant name="struts.xwork.chaining.copyErrors" value="true"></constant><constant name="struts.xwork.chaining.copyFieldErrors" value="true"></constant><constant name="struts.xwork.chaining.copyMessages" value="true"></constant><constant name="struts.multipart.maxSize" value="10485760"></constant><include file="struts-default.xml"></include><!-- <interceptor-stack name="fileUploadStack">
<interceptor-ref name="fileUpload" />
<interceptor-ref name="defaultStack" />
</interceptor-stack> --><package name="wxcm" extends="json-default"><!-- <interceptors>
<interceptor-stack name="fileUploadStack">
<interceptor-ref name="fileUpload" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors> --><!-- 图片文件上传 --><action name="imgUpLoad" class="imageUpload" method="imgUpLoad"><!-- <interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">20971520</param>
<param name="fileUpload.allowedTypesSet">image/jpeg,application/octet-stream,image/bmp,image/gif</param>
</interceptor-ref> --><interceptor-ref name="fileUploadStack"></interceptor-ref><result type="json" name="success"><param name="root">htglImgUrl
<param name="contentType">text/html
<param name="bufferSize">40960
<!-- <param name="contentType">image/jpeg,image/gif,image/bmp</param> -->
</result><result type="json" name="error"><param name="contentType">
text/html

</result></action><!-- 图片文件预览--><action name="showImg" class="imageUpload" method="showImg"><result name="imgReadSuccess" type="stream"><param name="contentType">image/jpeg,image/gif,image/bmp
<param name="inputName">imageStream
<param name="bufferSize">4096
</result></action><!-- 图片文件显示--><!-- <action name="toShowImage" class="imageDownload" method="toShowImage">
<result name="imgReadSuccess" type="stream">
<param name="contentType">image/jpeg,image/gif</param>
<param name="inputName">imageStream</param>
<param name="bufferSize">4096</param>
</result>
</action> --></package></struts>


3,图片上传action(ImageUpload.java)

package xtyl.action;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import common.util.SmbUtil;

public class ImageUpload extends ActionSupport {

/**
*
*/
private static final long serialVersionUID = 2834338485790652521L;

/**
* 图片文件
*/
protected File file = null;
protected String fileFileName = null;

private static String rootPath = null;

static{
rootPath = ServletActionContext.getServletContext().getRealPath("/");
}

/**
* 返回图片在服务器的路径
*/
private JSONArray htglImgUrl;

/**
* 编辑时需要显示的图片的名称
*/
private String imgPath = null;

/**
* 图片流
*/
private ByteArrayInputStream imageStream;

/**
* 预览图片
*
* @return String
*/
public String imgUpLoad() {
LOG.debug("method imgUpLoad start!");
// 复制到指定目录

//String fileName = "thisImgName" + fileFileName.substring(fileFileName.lastIndexOf("."));
String templatePath = rootPath + "uploadImgFile/" + fileFileName;

try {
FileUtils.copyFile(file, new File(templatePath));
toGenerateThumbnailImage(templatePath, 0.2f);
/*toGenerateThumbnailImage(templatePath, 0.3f);
toGenerateThumbnailImage(templatePath, 0.4f);
toGenerateThumbnailImage(templatePath, 0.5f);
toGenerateThumbnailImage(templatePath, 0.1f);*/
} catch (IOException e) {
LOG.error("图片复制失败");
}
try {
File file0 = new File(templatePath);
SmbUtil.smbPut(SmbUtil.remoteUrl, file0, file0.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String newImgName = toGetImgName(templatePath, 0.2f);
File fileThumb = new File(rootPath + "uploadImgFile/"+newImgName);
SmbUtil.smbPut(SmbUtil.remoteUrl, fileThumb, fileThumb.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject url = new JSONObject();
htglImgUrl = new JSONArray();
// String toShowImgPath = rootPath + "uploadImgFile/" + toGetImgName(rootPath + "uploadImgFile/"+fileFileName, 0.2f);
url.put("htglImgUrl", toGetImgName(rootPath + "uploadImgFile/"+fileFileName, 0.2f));
htglImgUrl.add(url);
return SUCCESS;

}

/**
* 生成缩略图
*
* @param srcImgPath
* @param scale
*/
private void toGenerateThumbnailImage(String srcImgPath, Float scale) {
if (srcImgPath == null || srcImgPath.isEmpty()) {
return ;
}
String newImgName = toGetImgName(srcImgPath, scale);
try {
String rootPath = ServletActionContext.getServletContext().getRealPath("/");
String newImgPath = rootPath + "uploadImgFile/";
try {
SmbFile sfile = new SmbFile(SmbUtil.remoteUrl);
if (!sfile.exists()) {
sfile.mkdirs();
}
} catch (Exception e) {
}
Thumbnails.of(srcImgPath).scale(scale).toFile(newImgPath+newImgName);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 获取指定比例的图片名称
* @param srcImgPath
* @param scale
* @return
*/
private String toGetImgName(String srcImgPath, Float scale) {
if (srcImgPath == null || srcImgPath.isEmpty()) {
return null;
}
File srcImgFile = new File(srcImgPath);
Long imgWidth = 0L;
Long imgHeight = 0L;
Long imgLength = 0L;
try {
FileInputStream fis = new FileInputStream(srcImgFile);
BufferedImage buff = ImageIO.read(srcImgFile);
// BufferedImage buff1 = ImageIO.read(new SmbFileInputStream(SmbUtil.serverUrl + imageUrl));
imgWidth = buff.getWidth() * 1L;
imgHeight = buff.getHeight() * 1L;
imgLength = srcImgFile.length();
fis.close();
} catch (FileNotFoundException e) {
System.err.println("所给的图片文件" + srcImgFile.getPath() + "不存在!计算图片尺寸大小信息失败!");
} catch (IOException e) {
System.err.println("计算图片" + srcImgFile.getPath() + "尺寸大小信息失败!");
}
System.out.println("imgWidth = " + imgWidth + " imgHeight = " + imgHeight + " imgLength = " + imgLength);
return toGetImgName(srcImgPath) + "_"
+ Integer.parseInt(new java.text.DecimalFormat("0").format(imgWidth * scale)) + "x"
+ Integer.parseInt(new java.text.DecimalFormat("0").format(imgHeight * scale))
+ srcImgPath.substring(srcImgPath.length() - 4, srcImgPath.length());
// System.out.println("newImgName = " + newImgName);
}

/**
* 获取图片名称
*
* @param imgPath
* @return
*/
private String toGetImgName(String imgPath) {
String str[] = imgPath.split("[\\/]");
if (str == null || str.length == 0) {
return null;
}
String tmpStr = str[str.length - 1];
return tmpStr.substring(0, tmpStr.length() - 4);
}

/**
* 显示图片
* @return
* @throws UnsupportedEncodingException
*/
public String showImg() throws UnsupportedEncodingException {

if (imgPath != null && !imgPath.isEmpty()) {
try {
// String rootPath = ServletActionContext.getServletContext().getRealPath("/");

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String timeStr = formatter.format(new Date());
String imgSavePath = SmbUtil.remoteUrl + "/" + timeStr + "/" + imgPath;

imageStream = SmbUtil.smbGet(imgSavePath);
/*ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream input =
new BufferedInputStream(new FileInputStream(imgPath));
byte[] bt = new byte[1024];
while (input.read(bt) > 0) {
bos.write(bt);
}
this.imageStream = new ByteArrayInputStream(bos.toByteArray());
if (bos != null) {
bos.close();
}
if (input != null) {
input.close();
}*/
} catch (Exception e) {
LOG.error("图片显示出错!");
}
}
return "imgReadSuccess";
}

public File getFile() {
return file;
}

public void setFile(File file) {
this.file = file;
}

public String getFileFileName() {
return fileFileName;
}

public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}

public JSONArray getHtglImgUrl() {
return htglImgUrl;
}

public void setHtglImgUrl(JSONArray htglImgUrl) {
this.htglImgUrl = htglImgUrl;
}

public String getImgPath() {
return imgPath;
}

public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}

public ByteArrayInputStream getImageStream() {
return imageStream;
}

public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}

}


4,spring配置文件(application.xml)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
"><!-- <bean id="propertyConfigurer"
class="com.usi.wxcm.common.util.WxcmPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/conf/DB.properties</value>
<value>/WEB-INF/conf/Mail.properties</value>
</list>
</property>
</bean> --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"><property name="driverClass"><value>${driverClassName}</value></property><property name="jdbcUrl"><value>${url}</value></property><property name="user"><value>${username}</value></property><property name="password"><value>${password}</value></property><property name="minPoolSize" value="5"></property><property name="maxPoolSize" value="15"></property><property name="initialPoolSize" value="10"></property><property name="maxIdleTime" value="60"></property><property name="acquireIncrement" value="10"></property><property name="maxStatements" value="0"></property><property name="acquireRetryAttempts" value="5"></property><property name="idleConnectionTestPeriod" value="60"></property><property name="breakAfterAcquireFailure" value="false"></property><property name="testConnectionOnCheckout" value="false"></property></bean><!--
<property name="defaultAutoCommit" value="true"></property>
<property name="validationQuery" value="select 1 from dual"></property>
--><!-- Database initializer. If any of the script fails, the initialization
stops. --><!--As an alternative, for embedded databases see <jdbc:embedded-database/>.
<jdbc:initialize-database data-source="dataSource"> <jdbc:script location="${location}"
encoding="UTF-8" /> </jdbc:initialize-database> --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop><!-- <prop key="hibernate.default_schema">wxcm</prop> --><prop key="hibernate.show_sql">true</prop><prop key="hibernate.autoReconnect">true</prop></props></property><!-- <property name="mappingResources">
<list>
<value>com/usi/wxcm/entity/User.hbm.xml </value>
<value>com/usi/wxcm/entity/DataDict.hbm.xml </value>
<value>com/usi/wxcm/entity/Role.hbm.xml</value>
<value>com/usi/wxcm/entity/ProjectCode.hbm.xml</value>
</list>
</property> --></bean><bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory"></property></bean><bean id="daoTemplate" abstract="true"><property name="hibernateTemplate"><ref bean="hibernateTemplate"></ref></property></bean><!-- 定义事务管理器(声明式的事务) --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- use declarative transaction management --><annotation-driven transaction-manager="transactionManager"></annotation-driven><!-- 图片显示 --><bean id="imageUpload" class="xtyl.action.ImageUpload" scope="prototype"></bean></beans>


5,web.xml配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml</param-value></context-param><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>*.action</url-pattern></filter-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><welcome-file-list><welcome-file>imgTest.jsp</welcome-file></welcome-file-list><session-config><session-timeout>30</session-timeout></session-config></web-app>

6,需要相关的js插件
jquery-1.11.1.min.js 和 ajaxfileupload.js


7,自己写的相关图片上传js代码(imgUpload.js)

function changeUrl(){
var path = $('#fileField1').val();
//alert("path==="+path);
var post = path.lastIndexOf("\\");
//alert("post==="+post);
$('#imageUrl').val(path.substring(post + 1, path.length));
$('#imageUrlTmp').val(path.substring(post + 1, path.length));
alert(path.substring(post + 1, path.length));
var imgup = document.getElementById("imageUrl");
if (imgup.value == "") {
return;
}
// 判断是否是图片格式
var imgname = imgup.value.substring(imgup.value.lastIndexOf("."), imgup.value.length);
imgname = imgname.toLowerCase();
/*if (!equalsIgnoreCase(imgname,'.jpg') && !equalsIgnoreCase(imgname, '.gif')) {
alert("请选择图片文件,谢谢!");
imgup.focus();
// 清空file里面的值
$("#imageUrl").attr("value", "");
$("#imageUrlTmp").attr("value", "");
} else {
// 显示图片
$.ajaxFileUpload({
url : 'imgUpLoad.action?'+new Date().getTime(),
secureuri : false,
fileElementId : 'fileField1',
dataType : 'json',
error:function(msg){
alert(" image error occured!!!"+msg);
},
success : function(result) {
$("#imgsrc").attr("src", "showImg.action?"+new Date().getTime()+"&imgPath="+result[0].htglImgUrl);
}
});
}*/
// 显示图片
$.ajaxFileUpload({
url : 'imgUpLoad.action?'+new Date().getTime(),
secureuri : false,
fileElementId : 'fileField1',
dataType : 'json',
error:function (data, status, e)//服务器响应失败处理函数
{
alert("errrrrrrr");
alert(data.msg);
alert(status);
alert(e);
},
success : function(result) {
$("#imgsrc").attr("src", "showImg.action?"+new Date().getTime()+"&imgPath="+result[0].htglImgUrl);
}
});
}

//忽略大小写比较字符串是否相等
function equalsIgnoreCase(str1, str2){
if(str1.toUpperCase() == str2.toUpperCase()){
return true;
}
return false;
}


8,pox.xml文件配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelversion>4.0.0</modelversion><groupid>com.XtylImage</groupid><artifactid>XtylImage</artifactid><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><properties><project.build.sourceencoding>UTF-8</project.build.sourceencoding><struts.version>2.3.1.2</struts.version><spring.version>4.0.2.RELEASE</spring.version><hibernate.version>4.3.6.Final</hibernate.version></properties><build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources><pluginmanagement><plugins><plugin><artifactid>maven-compiler-plugin</artifactid><version>2.3.2</version><inherited>true</inherited><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding></configuration></plugin></plugins></pluginmanagement></build><dependencymanagement><dependencies><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-core</artifactid><version>${struts.version}</version><exclusions><exclusion><groupid>javassist</groupid><artifactid>javassist</artifactid></exclusion></exclusions></dependency><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-json-plugin</artifactid><version>${struts.version}</version></dependency><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-spring-plugin</artifactid><version>${struts.version}</version><exclusions><exclusion><artifactid>spring-web</artifactid><groupid>org.springframework</groupid></exclusion><exclusion><artifactid>spring-beans</artifactid><groupid>org.springframework</groupid></exclusion><exclusion><artifactid>spring-context</artifactid><groupid>org.springframework</groupid></exclusion><exclusion><artifactid>spring-core</artifactid><groupid>org.springframework</groupid></exclusion></exclusions></dependency><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-convention-plugin</artifactid><version>${struts.version}</version></dependency><dependency><groupid>log4j</groupid><artifactid>log4j</artifactid><version>1.2.14</version></dependency><dependency><groupid>org.slf4j</groupid><artifactid>slf4j-api</artifactid><version>1.6.1</version></dependency><dependency><groupid>org.slf4j</groupid><artifactid>slf4j-log4j12</artifactid><version>1.6.0</version></dependency><dependency><groupid>junit</groupid><artifactid>junit</artifactid><version>4.10</version><scope>test</scope></dependency><dependency><groupid>org.hibernate</groupid><artifactid>hibernate-core</artifactid><version>${hibernate.version}</version></dependency><dependency><groupid>org.hibernate</groupid><artifactid>hibernate-entitymanager</artifactid><version>${hibernate.version}</version></dependency><dependency><groupid>net.sf.ehcache</groupid><artifactid>ehcache</artifactid><version>1.6.2</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-core</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-context</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-jdbc</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-orm</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-tx</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-web</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-test</artifactid><version>${spring.version}</version><scope>test</scope></dependency><dependency><groupid>org.hibernate</groupid><artifactid>hibernate-validator</artifactid><version>4.3.0.Final</version></dependency><dependency><groupid>commons-dbcp</groupid><artifactid>commons-dbcp</artifactid><version>1.4</version></dependency><dependency><groupid>commons-pool</groupid><artifactid>commons-pool</artifactid><version>1.5.6</version></dependency><dependency><groupid>commons-codec</groupid><artifactid>commons-codec</artifactid><version>1.5</version></dependency><dependency><groupid>net.sf.json-lib</groupid><artifactid>json-lib</artifactid><version>2.4</version><classifier>jdk15</classifier></dependency><dependency><groupid>javax.mail</groupid><artifactid>mail</artifactid><version>1.4</version></dependency><dependency><groupid>junit</groupid><artifactid>junit</artifactid><scope>test</scope><version>4.4</version></dependency></dependencies></dependencymanagement><dependencies><dependency><groupid>javax.servlet</groupid><artifactid>servlet-api</artifactid><version>2.5</version><scope>provided</scope></dependency><dependency><groupid>javax.servlet</groupid><artifactid>jstl</artifactid><version>1.2</version></dependency><dependency><groupid>javax.servlet.jsp</groupid><artifactid>jsp-api</artifactid><version>2.2</version><scope>provided</scope></dependency><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-core</artifactid></dependency><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-spring-plugin</artifactid></dependency><dependency><groupid>org.apache.struts</groupid><artifactid>struts2-json-plugin</artifactid></dependency><dependency><groupid>log4j</groupid><artifactid>log4j</artifactid></dependency><dependency><groupid>org.slf4j</groupid><artifactid>slf4j-api</artifactid></dependency><dependency><groupid>org.slf4j</groupid><artifactid>slf4j-log4j12</artifactid></dependency><dependency><groupid>org.hibernate</groupid><artifactid>hibernate-core</artifactid></dependency><dependency><groupid>org.hibernate</groupid><artifactid>hibernate-entitymanager</artifactid></dependency><dependency><groupid>net.sf.ehcache</groupid><artifactid>ehcache</artifactid></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-core</artifactid></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-context</artifactid></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-jdbc</artifactid></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-orm</artifactid></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-tx</artifactid></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-web</artifactid></dependency><dependency><groupid>org.hibernate</groupid><artifactid>hibernate-validator</artifactid></dependency><dependency><groupid>commons-dbcp</groupid><artifactid>commons-dbcp</artifactid></dependency><dependency><groupid>com.oracle</groupid><artifactid>ojdbc6</artifactid><version>11.2.0.1</version></dependency><dependency><groupid>commons-codec</groupid><artifactid>commons-codec</artifactid></dependency><dependency><groupid>org.apache.poi</groupid><artifactid>poi</artifactid><version>3.9</version></dependency><dependency><groupid>org.apache.poi</groupid><artifactid>poi-ooxml</artifactid><version>3.9</version></dependency><dependency><groupid>org.apache.poi</groupid><artifactid>poi-scratchpad</artifactid><version>3.9</version></dependency><dependency><groupid>org.apache.poi</groupid><artifactid>poi-ooxml-schemas</artifactid><version>3.9</version></dependency><dependency><groupid>net.sf.jxls</groupid><artifactid>jxls-core</artifactid><version>1.0.3</version></dependency><dependency><groupid>net.sf.jxls</groupid><artifactid>jxls-reader</artifactid><version>1.0.3</version></dependency><dependency><groupid>net.sf.json-lib</groupid><artifactid>json-lib</artifactid><classifier>jdk15</classifier></dependency><dependency><groupid>org.apache.commons</groupid><artifactid>commons-compress</artifactid><version>1.8.1</version></dependency><dependency><groupid>commons-validator</groupid><artifactid>commons-validator</artifactid><version>1.4.0</version></dependency><dependency><groupid>javax.mail</groupid><artifactid>mail</artifactid></dependency><dependency><groupid>jcifs</groupid><artifactid>jcifs</artifactid><version>1.3.17</version></dependency><!-- 缩略图配置 begin --><dependency><groupid>thumbnailator</groupid><artifactid>thumbnailator</artifactid><version>0.4.5</version></dependency><!-- 缩略图配置 end --><dependency><groupid>com.mchange</groupid><artifactid>c3p0</artifactid><version>0.9.5-pre10</version></dependency><dependency><groupid>junit</groupid><artifactid>junit</artifactid><scope>test</scope></dependency><dependency><groupid>org.quartz-scheduler</groupid><artifactid>quartz</artifactid><version>1.8.4</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-webmvc</artifactid><version>${spring.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-context-support</artifactid><version>${spring.version}</version></dependency></dependencies></project>

9,远程图片服务器相关参数文件(smbConfig.properties)

hostIP=172.17.2.23 #远程图片服务器ip
loginUser=wxcm #登陆用户名
loginPwd=Overseas123 #登陆密码
imagePath=wxcm2/xtylTest/images/xtylImages #存储图片文件夹


10,上传及预览用到的相关方法(SmbUtil.java)

package common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SmbUtil {
private static final Log LOG = LogFactory.getLog(SmbUtil.class);
/**
* 加载配置文件
*
* */
public static String serverUrl;
public static String remoteUrl;
public static String imageZipRemoteUrl;
public static String gysUploadImagRemoteUrl;
public static String gysUploadFileRemoteUrl;
public static String compareResultFileUrl;
static {
Properties prop = new Properties();
InputStream in = SmbUtil.class.getResourceAsStream("/smbConfig.properties");
try {
prop.load(in);
String hostIP = prop.getProperty("hostIP").trim();
String loginUser = prop.getProperty("loginUser").trim();
String loginPwd = prop.getProperty("loginPwd").trim();
String imagePath = prop.getProperty("imagePath").trim();
serverUrl = "smb://" + loginUser + ":" + loginPwd + "@" + hostIP;
remoteUrl = "smb://" + loginUser + ":" + loginPwd + "@" + hostIP + "/" + imagePath;
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 把文件上传到局域网共享文件下
*
* @param remoteUrl 共享电脑路径 如:smb//administrator:123456@172.16.10.136/smb
* @param localFile File对象
* @param fileName 保存的文件名
*/
public static String smbPut(String remoteUrl, File localFile, String fileName) throws IOException {
if (localFile == null || !localFile.exists()) {
return null;
}
InputStream in = null;
OutputStream out = null;
String remoteFileName = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String timeStr = formatter.format(new Date());
/*
* SmbFile sfile = new SmbFile(remoteUrl + File.separator + timeStr + File.separator); if (!sfile.exists()) { sfile.mkdirs(); }
*/
String imgSavePath = SmbUtil.remoteUrl + "/" + timeStr + "/";
try {
SmbFile sfile = new SmbFile(imgSavePath);
if (!sfile.exists()) {
sfile.mkdirs();
}
} catch (Exception e) {
}
SmbFile remoteFile = new SmbFile(remoteUrl + File.separator + timeStr + File.separator + fileName);
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[1024];
while ((in.read(buffer)) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
remoteFileName = remoteFile.getName();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}

}
return remoteFileName;
}

/**
* 把文件上传到局域网共享文件下(编辑书目时,如果图片被替换,则删除原图片保存新图片)
*
* @param remoteUrl 共享电脑路径 如:smb//administrator:123456@172.16.10.136/smb
* @param localFile File对象
* @param fileName 保存的文件名
* @param fileNameBeforeUpd 被编辑前保存的图片名称
*/
/*
* public static String smbPut(String remoteUrl, File localFile, String fileName, String fileNameBeforeUpd) throws IOException { // 删除原图片 SmbFile remoteFileDel = new SmbFile(remoteUrl + File.separator + fileNameBeforeUpd); // 路径为文件且不为空则进行删除 if (remoteFileDel.isFile() && remoteFileDel.exists()) { remoteFileDel.delete(); }
*
* // 保存新图片 InputStream in = null; OutputStream out = null; String remoteFileName = null; try { // String fileName = localFile.getName(); SmbFile remoteFile = new SmbFile(remoteUrl + File.separator + fileName); in = new BufferedInputStream(new FileInputStream(localFile)); out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile)); byte[] buffer = new byte[1024]; while ((in.read(buffer)) != -1) { out.write(buffer); buffer = new byte[1024]; } remoteFileName = remoteFile.getName(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); }
*
* } return remoteFileName; }
*/

/**
* 从文件服务器中读取图片文件输出到输出流中
*
* @param remoteUrl
* @param out
*/
public static void smbGet(String remoteUrl, OutputStream out) {
InputStream in = null;
try {
SmbFile smbFile = new SmbFile(remoteUrl);
in = new BufferedInputStream(new SmbFileInputStream(smbFile));
byte[] buffer = new byte[1024];
while ((in.read(buffer)) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 根据图片名称查找图片
*
* @return
* @throws BaseDBException
*/
/*
* public static ByteArrayInputStream smbGet(String imageName) throws BaseDBException { ByteArrayInputStream imageStream = null; if (imageName != null && !imageName.isEmpty()) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream input = new BufferedInputStream( new SmbFileInputStream(SmbUtil.remoteUrl + File.separator + imageName)); byte[] bt = new byte[1024]; while (input.read(bt) > 0) { bos.write(bt); } imageStream = new ByteArrayInputStream(bos.toByteArray()); if (bos != null) { bos.close(); } if (input != null) { input.close(); } } catch (Exception e) { LOG.error("图片显示出错!"); e.printStackTrace(); } } return imageStream; }
*/

/**
* 根据图片服务器路径查找图片
*
* @return
* @throws BaseDBException
*/
public static ByteArrayInputStream smbGet(String imageUrl) throws Exception {
ByteArrayInputStream imageStream = null;
if (imageUrl != null && !imageUrl.isEmpty()) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
SmbFile sfile = new SmbFile(imageUrl);
if(imageUrl == null || imageUrl.isEmpty()){
return null;
}
String subImgUrl = imageUrl.substring(imageUrl.length()-3,imageUrl.length());
/*if(!"jpg".equalsIgnoreCase(subImgUrl) && !"gif".equalsIgnoreCase(subImgUrl)){
return null;
}*/
if (!sfile.exists()) {
return imageStream;
}
InputStream input = new BufferedInputStream(new SmbFileInputStream(imageUrl));
byte[] bt = new byte[1024];
while (input.read(bt) > 0) {
bos.write(bt);
}
imageStream = new ByteArrayInputStream(bos.toByteArray());
if (bos != null) {
bos.close();
}
if (input != null) {
input.close();
}
} catch (Exception e) {
LOG.error("图片显示出错!");
e.printStackTrace();
}
}
return imageStream;
}

/**
* 根据文件服务器路径查找文件
*
* @return
* @throws BaseDBException
*/
public static InputStream smbGetFile(String fileUrl) throws Exception {
InputStream input = null;
if (fileUrl != null && !fileUrl.isEmpty()) {
try {
SmbFile sfile = new SmbFile(SmbUtil.gysUploadFileRemoteUrl +"/"+ fileUrl);
if(fileUrl == null || fileUrl.isEmpty()){
return input;
}
if (!sfile.exists()) {
return input;
}
input = new BufferedInputStream(new SmbFileInputStream(SmbUtil.gysUploadFileRemoteUrl+"/" + fileUrl));

} catch (Exception e) {
LOG.error("图片显示出错!");
e.printStackTrace();
}
}
return input;
}
/**
* 根据key读取配置文件value值的方法
*
* @param key
* @return
*/
public static String readProperties(String key) {
Properties prop = new Properties();
InputStream in = SmbUtil.class.getResourceAsStream("/smbConfig.properties");
String value = "";
try {
prop.load(in);
value = prop.getProperty(key);
} catch (IOException e1) {
e1.printStackTrace();
}
return value;
}

/**
* 根据图片名称移动服务器上的图片
*
* @param key
* @return
*/
public static String movePicByName(String nowPicName, String newPicName, String supplierCode, Boolean flag) {
try {
File ff = new File(nowPicName);
try {
newPicName = newPicName + nowPicName.substring(nowPicName.lastIndexOf("."));
} catch (Exception e) {
return null;
}
SmbFile sf =
new SmbFile(SmbUtil.gysUploadImagRemoteUrl + File.separator + supplierCode + File.separator
+ nowPicName);
if (sf.exists()) {
if (flag) {
return "exists";
}
OutputStream o = new FileOutputStream(ff);
SmbUtil.smbGet(SmbUtil.gysUploadImagRemoteUrl + File.separator + supplierCode + File.separator
+ nowPicName, o);
SmbUtil.smbPut(SmbUtil.remoteUrl, ff, newPicName);
ff.delete();
return "true";
} else {
return null;
}
} catch (SmbException e) {
return null;
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值