基于cxf的app文件上传接口(带回显功能)
1.SaleImpl
@Override
public String uploadPic(final List<Attachment> attachments) {
return this.filterException(new MethodCallBack() { @Override
public String doProcessMethod() throws Exception {
List<FileUploadVo> fileVos = transform2FileUploadVo(attachments);
String rs = nhSalePerformancePicIService.saveUploadPic(fileVos);
return rs;
}
});
}
这里的实体 Attachment 类是cxf提供的附件类 org.apache.cxf.jaxrs.ext.multipart.Attachment
2.附件转换方法 transform2FileUploadVo BaseWsServer.java
package cn.maitian.newhouse.framework.core.base.ws; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List; import javax.activation.DataHandler; import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;
import org.apache.log4j.Logger; import cn.maitian.core.persistence.db.JugHelper;
import cn.maitian.newhouse.framework.core.base.bean.MethodCallBack;
import cn.maitian.newhouse.framework.core.base.bean.WsResultJson;
import cn.maitian.newhouse.framework.core.base.vo.FileUploadVo;
import cn.maitian.newhouse.framework.core.exception.AppClientException;
import cn.maitian.newhouse.framework.core.exception.AppSysException;
import cn.maitian.newhouse.framework.core.i18n.IAppPropertiesMsg;
import cn.maitian.newhouse.framework.core.util.AppFileUploadUtils;
import cn.maitian.newhouse.framework.system.model.NhAttachment; /**
* WebService服务端基础类
*
* @author LXINXIN
* @company MAITIAN
* @version 1.0
*/
public class BaseWsServer { /**
* 日志
*/
protected final Logger logger = Logger.getLogger(getClass()); /**
* 处理客服端异常信息
*/
private IAppPropertiesMsg appExceptionClientMsg; /**
* 处理系统端异常信息
*/
private IAppPropertiesMsg appExceptionSystemMsg; /**
* 过滤文本格式
*/
final static String[] TEXT_TYPE = new String[] { "text/plain", "text/plain;charset=utf-8" }; /**
* <h1>统一处理异常和记录日志</h1>
*
* @param callback
* MethodCallBack 通过doProcessMethod进行逻辑的处理
* @return ResultJson
*/
public String filterException(MethodCallBack callback) {
String msg = "";
String code = "";
try {
// 获取拦截器message内容
Message message = PhaseInterceptorChain.getCurrentMessage();
AppSysException se = message.getContent(AppSysException.class);
// 内容不为空,则证明拦截器异常,抛出异常信息
if (se != null) {
// 不要再注释掉提交到CVS上了,个人调试可以注释掉
throw se;
}
return callback.doProcessMethod();
} catch (AppClientException ce) {
ce.printStackTrace();
logger.error(ce);
code = ce.getCode();
String[] params = ce.getParams();
msg = appExceptionClientMsg.getMessage(code, params);
} catch (AppSysException se) {
se.printStackTrace();
logger.error(se);
code = se.getCode();
String[] params = se.getParams();
msg = appExceptionSystemMsg.getMessage(code, params);
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
code = "CE900000";
msg = appExceptionClientMsg.getMessage(code);
}
return WsResultJson.failure(msg, null, code);
} /**
* 附件转换
*
* @param attachments
* 附件集合
* @return List 文件上传的值对象集合
*/
protected List<FileUploadVo> transform2FileUploadVo(List<Attachment> attachments) throws IOException {
if (attachments == null || attachments.size() <= 0) {
return null;
}
List<FileUploadVo> result = new ArrayList<FileUploadVo>();
for (Attachment attachment : attachments) {
FileUploadVo fuv = new FileUploadVo();
// 获取表单文本域类型
String contentType = attachment.getContentType().toString();
// 过滤非文件类型
if (Arrays.asList(TEXT_TYPE).contains(contentType.toLowerCase())) {
continue;
}
DataHandler dh = attachment.getDataHandler();
fuv.setInputStream(dh.getInputStream());
// 获取上传的原文件名
String oldFileName = dh.getName();
String originalFileName = AppFileUploadUtils.getOriginalFileName(oldFileName);
// 获取文件源文件后缀名
String fileExtendName = AppFileUploadUtils.getFileExtension(oldFileName);
// 生成新文件名
String newFileName = JugHelper.generalUUID();
NhAttachment lvAttachment = new NhAttachment();
lvAttachment.setId(newFileName);
lvAttachment.setOriginalFileName(originalFileName);
lvAttachment.setStorageFileName(newFileName);
lvAttachment.setFileExtendName(fileExtendName);
lvAttachment.setFileSize(null);
lvAttachment.setUploadFilePath(null);
lvAttachment.setUploadTime(null);
lvAttachment.setStateSign(NhAttachment.STATE_SIGN_USE);
fuv.setAttachment(lvAttachment);
result.add(fuv);
}
return result;
} /**
* @return the appExceptionClientMsg
*/
public IAppPropertiesMsg getAppExceptionClientMsg() {
return appExceptionClientMsg;
} /**
* @param appExceptionClientMsg
* the appExceptionClientMsg to set
*/
public void setAppExceptionClientMsg(IAppPropertiesMsg appExceptionClientMsg) {
this.appExceptionClientMsg = appExceptionClientMsg;
} /**
* @return the appExceptionSystemMsg
*/
public IAppPropertiesMsg getAppExceptionSystemMsg() {
return appExceptionSystemMsg;
} /**
* @param appExceptionSystemMsg
* the appExceptionSystemMsg to set
*/
public void setAppExceptionSystemMsg(IAppPropertiesMsg appExceptionSystemMsg) {
this.appExceptionSystemMsg = appExceptionSystemMsg;
} protected String getThreadId() {
String qid = "[" + Thread.currentThread().getId() + ":@" + new Date().getTime() + "@]";
logger.error("---action in---> " + qid);
return qid;
} protected String getMethodDebugMsg(String qid, long startTime, String msg) {
long endTime = System.currentTimeMillis();
logger.error(msg + "---aticon method out---> " + qid + " {" + (endTime - startTime) + "}");
return qid;
} protected String getActionDebugMsg(String qid, long startTime, String msg) {
long endTime = System.currentTimeMillis();
logger.error(msg + "---action out total time---> " + qid + " {" + (endTime - startTime) + "}");
return qid;
} }
FileUploadVo.java
package cn.maitian.newhouse.framework.core.base.vo; import java.io.InputStream;
import java.io.Serializable; import cn.maitian.newhouse.framework.system.model.NhAttachment; /**
* 文件上传的值对象
*
* @author LXINXIN
* @company MAITIAN
* @version 1.0
*/
public class FileUploadVo implements Serializable{ /**
*
*/
private static final long serialVersionUID = -3384430691991762476L; /**
* 文件的IO流
*/
private InputStream inputStream; /**
* 附件
*/
private NhAttachment attachment; /**
* @return the inputStream
*/
public InputStream getInputStream() {
return inputStream;
} /**
* @param inputStream
* the inputStream to set
*/
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
} /**
* @return the attachment
*/
public NhAttachment getAttachment() {
return attachment;
} /**
* @param attachment
* the attachment to set
*/
public void setAttachment(NhAttachment attachment) {
this.attachment = attachment;
} }
NhAttachment.java
package cn.maitian.newhouse.framework.system.model; import java.io.Serializable; import cn.maitian.newhouse.framework.core.base.model.BaseEntity;
import cn.maitian.webx.model.IDomainObject; /**
* 附件数据信息实体
*
* @author MGS
* @company ISOFTSTONE
* @version 1.0
*/
public class NhAttachment extends BaseEntity implements IDomainObject, Serializable { private static final long serialVersionUID = 875425364068338655L; /**
* 状态标志 0表示正常,1代表停用,默认是0
*/
public static final int STATE_SIGN_USE = 0;
/**
* 不可用状态
*/
public static final int STATE_SIGN_STOP = 1; /**
* 文件ID号
*/
private String id; /**
* 原始文件名
*/
private String originalFileName; /**
* 新文件名
*/
private String storageFileName; /**
* 文件扩展名
*/
private String fileExtendName; /**
* 文件尺寸,按字节存储
*/
private Long fileSize; /**
* 上传文件路径
*/
private String uploadFilePath; /**
* 上传时间
*/
private java.util.Date uploadTime; /**
* 状态标志,此字段预留,0表示正常,1代表停用,默认是0
*/
private Integer stateSign; /**
* 临时字段、存储当前图片是第几张
*/
private Integer sortNum;
/**
* 上传后图片服务器访问路径
*/
private String accessFilePath; /**
* @return the id
*/
public String getId() {
return id;
} /**
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
} /**
* @return the originalFileName
*/
public String getOriginalFileName() {
return originalFileName;
} /**
* @param originalFileName
* the originalFileName to set
*/
public void setOriginalFileName(String originalFileName) {
this.originalFileName = originalFileName;
} /**
* @return the storageFileName
*/
public String getStorageFileName() {
return storageFileName;
} /**
* @param storageFileName
* the storageFileName to set
*/
public void setStorageFileName(String storageFileName) {
this.storageFileName = storageFileName;
} /**
* @return the fileExtendName
*/
public String getFileExtendName() {
return fileExtendName;
} /**
* @param fileExtendName
* the fileExtendName to set
*/
public void setFileExtendName(String fileExtendName) {
this.fileExtendName = fileExtendName;
} /**
* @return the uploadFilePath
*/
public String getUploadFilePath() {
return uploadFilePath;
} /**
* @param uploadFilePath
* the uploadFilePath to set
*/
public void setUploadFilePath(String uploadFilePath) {
this.uploadFilePath = uploadFilePath;
} /**
* @return the uploadTime
*/
public java.util.Date getUploadTime() {
return uploadTime;
} /**
* @param uploadTime
* the uploadTime to set
*/
public void setUploadTime(java.util.Date uploadTime) {
this.uploadTime = uploadTime;
} /**
* @return the stateSign
*/
public Integer getStateSign() {
return stateSign;
} /**
* @param stateSign
* the stateSign to set
*/
public void setStateSign(Integer stateSign) {
this.stateSign = stateSign;
} /**
* @return the fileSize
*/
public Long getFileSize() {
return fileSize;
} /**
* @param fileSize
* the fileSize to set
*/
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
// 设置默认值
if (this.fileSize == null) {
this.fileSize = 0L;
}
} /**
* 拼接为完整文件名
*
* @return 完整文件名
*/
public String getFullFileName() {
return this.storageFileName + "." + this.fileExtendName;
} /**
* @return the sortNum
*/
public Integer getSortNum() {
return sortNum;
} /**
* @param sortNum
* the sortNum to set
*/
public void setSortNum(Integer sortNum) {
this.sortNum = sortNum;
} /**
* @return the accessFilePath
*/
public String getAccessFilePath() {
return accessFilePath;
} /**
* @param accessFilePath
* the accessFilePath to set
*/
public void setAccessFilePath(String accessFilePath) {
this.accessFilePath = accessFilePath;
} }
3.上传方法 saveUploadPic
NhSalePerformancePicServiceImpl
package cn.maitian.newhouse.modules.salePerformancepic.service.impl; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import cn.maitian.newhouse.framework.core.base.bean.WsResultJson;
import cn.maitian.newhouse.framework.core.base.service.impl.BaseServiceImpl;
import cn.maitian.newhouse.framework.core.base.vo.FileUploadVo;
import cn.maitian.newhouse.framework.core.exception.AppSysException;
import cn.maitian.newhouse.framework.core.util.AppFileUploadUtils;
import cn.maitian.newhouse.framework.core.util.AppFileUploadUtils.ImageType;
import cn.maitian.newhouse.framework.core.util.AppPropUtil;
import cn.maitian.newhouse.framework.system.dao.NhAttachmentIDao;
import cn.maitian.newhouse.framework.system.model.NhAttachment;
import cn.maitian.newhouse.modules.salePerformancepic.dao.NhSalePerformancePicIDao;
import cn.maitian.newhouse.modules.salePerformancepic.model.NhSalePerformancePic;
import cn.maitian.newhouse.modules.salePerformancepic.service.NhSalePerformancePicIService;
import cn.maitian.webx.support.Page; /**
*
*
* @company
* @version 1.0
*/
public class NhSalePerformancePicServiceImpl extends BaseServiceImpl implements NhSalePerformancePicIService { /**
* Spring注入
*/
private NhSalePerformancePicIDao nhSalePerformancePicIDao; private NhAttachmentIDao nhAttachmentIDao; @Override
public String saveUploadPic(List<FileUploadVo> fileVos) {
if (fileVos == null || fileVos.isEmpty()) {
return null;
}
// 返回的结果信息
List<Map<String,Object>> rs = new ArrayList<Map<String,Object>>();
// 按日期生成文件夹
Integer sortNum = 1;
for (FileUploadVo fuv : fileVos) {
InputStream ins = fuv.getInputStream();
NhAttachment attachment = fuv.getAttachment();
String fullFileName = attachment.getStorageFileName() + "." + attachment.getFileExtendName();
// 文件上传
Map<String, String> uploadResult = null;
try {
uploadResult = AppFileUploadUtils.upload(ins, fullFileName);
} catch (IOException e) {
e.printStackTrace();
throw new AppSysException("SE101007");
}
attachment.setFileSize(Long.valueOf(uploadResult.get(AppFileUploadUtils.KEY_FILE_SIZE)));
attachment.setUploadFilePath(uploadResult.get(AppFileUploadUtils.KEY_RELATIVE_PATH));
attachment.setUploadTime(new Date());
String webServerUrl = AppPropUtil.getPropValue(AppPropUtil.Keys.DOWNLOAD_FILE_HTTP );
String accessPath =webServerUrl+AppFileUploadUtils.genThubnFilePath(attachment.getUploadFilePath(), ImageType.MIDDLE) ;
attachment.setAccessFilePath(accessPath); nhAttachmentIDao.doSave(attachment);
attachment.setSortNum(sortNum);
sortNum++;
Map<String,Object> picRs = new HashMap<String, Object>();
picRs.put("picId", attachment.getId()); String webAccessUrl =webServerUrl+ AppFileUploadUtils.genThubnFilePath(attachment.getUploadFilePath(),ImageType.SMALL); picRs.put("url", webAccessUrl);
rs.add(picRs);
}
Page page = new Page();
page.setResult(rs);
return WsResultJson.success(page);
} @Override
public void saveOrUpdate(NhSalePerformancePic vo) {
nhSalePerformancePicIDao.saveOrUpdateNhSalePerformancePic(vo);
} @Override
public NhSalePerformancePic findById(String id) {
return nhSalePerformancePicIDao.findNhSalePerformancePicById(id);
} @Override
public void deleteById(String id) {
nhSalePerformancePicIDao.deleteNhSalePerformancePicById(id);
} @Override
public void deleteByIds(String[] ids) {
nhSalePerformancePicIDao.deleteNhSalePerformancePicByIds(ids);
}
@Override
public List<NhSalePerformancePic> findAll() {
return nhSalePerformancePicIDao.findAllNhSalePerformancePic();
} @Override
public Page searchPage(int pageNo, int pageSize, String orderByStr) {
return nhSalePerformancePicIDao.searchNhSalePerformancePic(pageNo, pageSize, orderByStr);
} @Override
public Page searchPage(int pageNo, int pageSize, String orderByStr, NhSalePerformancePic vo) {
return nhSalePerformancePicIDao.searchNhSalePerformancePic(pageNo, pageSize, orderByStr, vo);
} /**
* @param nhSalePerformancePicIDao
* the nhSalePerformancePicIDao to set
*/
public void setNhSalePerformancePicIDao(NhSalePerformancePicIDao nhSalePerformancePicIDao) {
this.nhSalePerformancePicIDao = nhSalePerformancePicIDao;
} /**
*
* @param nhAttachmentIDao
* nhAttachmentIDao to set
*/
public void setNhAttachmentIDao(NhAttachmentIDao nhAttachmentIDao) {
this.nhAttachmentIDao = nhAttachmentIDao;
} @Override
public List<NhSalePerformancePic> findAllNhSalePerformancePicByPerformacneId(
String performancceId) {
// TODO Auto-generated method stub
return nhSalePerformancePicIDao.findAllNhSalePerformancePicByPerformacneId(performancceId);
} }
4.AppFileUploadUtils
/**
*
*/
package cn.maitian.newhouse.framework.core.util; import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile; import javax.imageio.ImageIO;
import javax.swing.ImageIcon; import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang.StringUtils; import cn.maitian.newhouse.framework.core.exception.AppClientException;
import net.coobird.thumbnailator.Thumbnails; /**
* 文件上传通用方法
*
* @author MGS
* @company ISOFTSTONE
* @version 1.0
*/
public class AppFileUploadUtils {
/**
* 附件上传目录
*/
private static final String FILE_TYPE_UPLOAD = "/upload";
/**
* 头像上传目录
*/
private static final String FILE_TYPE_HEADPIC = "/headpic";
/**
* 附件上传临时目录
*/
private static final String FILE_TYPE_TMP = "/tmp";
/**
* 文件分隔符
*/
private static final String SEPARATOR = "/"; /**
* 头像扩展名
*/
private static final String HEAD_EXT = ".jpg"; /**
* key:文件大小
*/
public static final String KEY_FILE_SIZE = "fileSize";
/**
* key:文件相对路径
*/
public static final String KEY_RELATIVE_PATH = "relativePath";
/**
* key:下载文件相对路径
*/
public static final String KEY_RELATIVE_DOWNLOAD_PATH = "relativeDownloadPath";
/**
* ipa文件
*/
public static final String PLIST_FILE = "plist";
/**
* ipa文件
*/
public static final String IPA_FILE = "ipa"; /**
* 图片类型
*/
public enum ImageType {
/**
* 小图片连接名
*/
SMALL("_s"),
/**
* 中图片连接名
*/
MIDDLE("_m"),
/**
* 大图片连接名
*/ LARGE("_l"),
/**
* banner图片
*/
BANNER("_b"); private String val; private ImageType(String val) {
this.val = val;
} /**
* 输出值
*
* @return Integer
*/
public String value() {
return this.val;
}
} /**
* 文件上传
*
* @param inputStream
* 文件流
* @param fullFileName
* 完整文件名
* @return 相对路径
* @throws IOException
* 异常
*/
public static String uploadHead(InputStream inputStream, String fullFileName) throws IOException {
String relativePath = FILE_TYPE_HEADPIC + getFileDatePath();
if (AppStringUtils.isEmpty(relativePath)) {
return null;
}
if (AppStringUtils.isEmpty(fullFileName)) {
return null;
}
fullFileName = getOriginalFileName(fullFileName) + HEAD_EXT;
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传基础路径
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
// 文件上传的相对路径
String relativeFilePath = "";
// 文件上传的完整路径
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(inputStream);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
relativeFilePath = relativePath + SEPARATOR + fullFileName;
fullFilePath = basePath + relativeFilePath;
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(new File(basePath + relativeFilePath)));
// 写入文件
Streams.copy(in, out, true);
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
} // 生成头像小图
genSmallThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.SMALL));
// 生成头像中图
genMiddleThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.MIDDLE));
// 生成头像大图
genLargeThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.LARGE));
return relativeFilePath;
} /**
* 根据类型生成缩率图路径
*
* @param srcFilePath
* 原始文件名
* @param it
* 图片类型
* @return String
*/
public static String genThubnFilePath(String srcFilePath, ImageType it) {
if (srcFilePath == null || srcFilePath.trim().length() == 0) {
return null;
}
// . 之前的字符串
String prefix = getOriginalFileName(srcFilePath);
// . 之后的字符串
String suffix = getFileExtension(srcFilePath);
// 根据类型生成缩率图路径
String thubnFilePath = prefix + it.value() + "." + suffix;
return thubnFilePath;
} /**
* 文件上传
*
* @param inputStream
* 文件流
* @param fullFileName
* 完整文件名
* @return 相对路径
* @throws IOException
* 异常
*/
public static Map<String, String> upload(InputStream inputStream, String fullFileName) throws IOException {
Map<String, String> result = new HashMap<String, String>();
String fileSize = "0";
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
String relativePath = FILE_TYPE_UPLOAD + getFileDatePath();
// 完整文件名称
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(inputStream);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
fullFilePath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(fullFilePath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
fileSize = String.valueOf(f.length());
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
// 如果是图片,生成大中小图片
if (isImage(fullFileName)) {
// 生成头像小图
genSmallThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.SMALL));
// 生成头像中图
genMiddleThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.MIDDLE));
// 生成头像大图
genLargeThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.LARGE));
}
// 大小
result.put(KEY_FILE_SIZE, fileSize);
// 相对路径
result.put(KEY_RELATIVE_PATH, relativePath + SEPARATOR + fullFileName); return result;
} /**
* @param inputStream
* 流
* @param fullFileName
* 文件名
* @return Map<String, String>
* @throws IOException
* 异常
*/
public static Map<String, String> uploadTemp(InputStream inputStream, String fullFileName) throws IOException {
Map<String, String> result = new HashMap<String, String>();
String fileSize = "0";
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
String relativePath = FILE_TYPE_TMP + getFileDatePath();
// 完整文件名称
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(inputStream);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
fullFilePath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(fullFilePath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
fileSize = String.valueOf(f.length());
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
// 大小
result.put(KEY_FILE_SIZE, fileSize);
// 相对路径
result.put(KEY_RELATIVE_PATH, relativePath + SEPARATOR + fullFileName); return result;
} /**
* 安卓文件上传
*
* @param inputStream
* 文件流
* @param fullFileName
* 完整文件名
* @param version
* 版本号
* @return 相对路径
* @throws IOException
* 异常
*/
public static Map<String, Object> uploadAndroid(InputStream inputStream, String fullFileName, String version)
throws IOException {
Map<String, Object> result = new HashMap<String, Object>();
int fileSize = 0;
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
// 安卓上传路径
String androidUploadPath = AppPropUtil.getPropValue(AppPropUtil.Keys.ANDROID_UPLOAD_PREFIX);
String relativePath = androidUploadPath + SEPARATOR + version;
// 完整文件名称
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(inputStream);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
fullFilePath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(fullFilePath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
fileSize = (int) f.length();
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
// 大小
result.put(KEY_FILE_SIZE, fileSize);
// 相对路径
result.put(KEY_RELATIVE_PATH, relativePath + SEPARATOR + fullFileName);
return result;
} /**
* 把文件写到固定目标文件夹下,返回目标文件路径
*
* @param is
* 流
* @param fullFileName
* 文件名
* @param version
* 版本
*
*
* @return Map<String, Object>
* @throws IOException
* 异常
*/
public static Map<String, Object> uploadIos(InputStream is, String fullFileName, String version)
throws IOException {
// 目标文件路径
String targetPath = "";
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
// ios上传路径
String isoUpload = AppPropUtil.getPropValue(AppPropUtil.Keys.IOS_UPLOAD_PREFIX);
String relativePath = isoUpload + SEPARATOR + version;
try {
// 获得文件输入流
in = new BufferedInputStream(is);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
targetPath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(targetPath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
String basePathHttps = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTPS);
return unzip(targetPath, basePathHttps + relativePath, false);
} /**
* 解压缩zip包
*
* @param zipFilePath
* zip文件的全路径
* @param unzipFilePath
* 解压后的文件保存的路径
* @param includeZipFileName
* 解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含
* @return Map<String, Object>
* @throws IOException
* 异常
* @throws ZipException
* 异常
*/
@SuppressWarnings("resource")
public static Map<String, Object> unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName)
throws ZipException, IOException {
Map<String, Object> map = new HashMap<String, Object>();
if (AppStringUtils.isEmpty(zipFilePath) || AppStringUtils.isEmpty(unzipFilePath)) {
return map;
}
File zipFile = new File(zipFilePath);
// 如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if (includeZipFileName) {
String fileName = zipFile.getName();
if (AppStringUtils.isNotEmpty(fileName)) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
unzipFilePath = unzipFilePath + File.separator + fileName;
}
// 创建解压缩文件保存的路径
File unzipFileDir = new File(unzipFilePath);
if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
unzipFileDir.mkdirs();
} // 开始解压
ZipEntry entry = null;
String entryFilePath = null, entryDirPath = null;
File entryFile = null, entryDir = null;
int index = 0, count = 0, bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
ZipFile tempZip = new ZipFile(zipFile);
@SuppressWarnings("unchecked")
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) tempZip.entries();
boolean isNoHasIpa = true;
boolean isNoHasPlist = true;
// 循环对压缩包里的每一个文件进行解压
while (entries.hasMoreElements()) {
entry = entries.nextElement();
String fileName = entry.getName();
// 构建压缩包中一个文件解压后保存的文件全路径
entryFilePath = unzipFilePath + SEPARATOR + fileName;
// 构建解压后保存的文件夹路径
index = entryFilePath.lastIndexOf(SEPARATOR);
if (index != -1) {
entryDirPath = entryFilePath.substring(0, index);
} else {
entryDirPath = "";
}
entryDir = new File(entryDirPath);
// 如果文件夹路径不存在,则创建文件夹
if (!entryDir.exists() || !entryDir.isDirectory()) {
entryDir.mkdirs();
} // 创建解压文件
entryFile = new File(entryFilePath);
// if (entryFile.exists()) {
// 检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
// SecurityManager securityManager = new SecurityManager();
// securityManager.checkDelete(entryFilePath);
// 删除已存在的目标文件
// entryFile.delete();
// } // 写入文件
bos = new BufferedOutputStream(new FileOutputStream(entryFile));
bis = new BufferedInputStream(tempZip.getInputStream(entry));
while ((count = bis.read(buffer, 0, bufferSize)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
bos.close(); // 获取文件后缀名
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (IPA_FILE.equalsIgnoreCase(suffix)) {
isNoHasIpa = false;
}
// plist文件
if (PLIST_FILE.equalsIgnoreCase(suffix)) {
isNoHasPlist = false;
// 大小
map.put(KEY_FILE_SIZE, (int) zipFile.length());
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTPS);
entryFilePath = entryFilePath.replace(basePath, "");
// plist相对路径
map.put(KEY_RELATIVE_PATH, entryFilePath);
}
}
if (isNoHasIpa || isNoHasPlist) {
throw new AppClientException("CE104008");
}
String bph = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
map.put(KEY_RELATIVE_DOWNLOAD_PATH, zipFilePath.replace(bph, ""));
return map;
} /**
* @param targetPath
* 文件的相对路径
*/
public static void deleteOriginalFile(String targetPath) {
// 文件的相对路径
File file = new File(targetPath);
// 若文件存在,则删除文件
if (file.exists()) {
file.delete();
}
} /**
* 获取文件的名称(不包括后缀)
*
* @param fileName
* 文件全名称
* @return 文件名(不含后缀)
*/
public static String getOriginalFileName(String fileName) {
// 文件名中不包括 . 则认为文件非法
if (!fileName.contains(".")) {
return "";
}
// 截取文件后缀
return fileName.substring(0, fileName.lastIndexOf("."));
} /**
* 获取文件名称后缀
*
* @param fileName
* 文件全名称
* @return 文件后缀
*/
public static String getFileExtension(String fileName) {
// 文件名中不包括 . 则认为文件非法
if (!fileName.contains(".")) {
return "";
}
// 截取文件后缀
return fileName.substring(fileName.lastIndexOf(".") + 1);
} /**
* 根据用户ID生成用户头像地址
*
* @param userId
* 用户ID
* @return 头像地址
*/
public static String getHeadFilePathByUserId(String userId) {
if (AppStringUtils.isEmpty(userId)) {
return "";
}
String substrValue = userId.substring(userId.length() - 2);
int value = hexadecimalConvertDecimalism(substrValue);
int cal = value % 50;
return SEPARATOR + String.valueOf(cal);
} /**
* 十六进制转换成十进制
*
* @param hexadecimal
* 十六进制参数值
* @return 十进制值
*/
public static int hexadecimalConvertDecimalism(String hexadecimal) {
// 十六进制转化为十进制
return Integer.parseInt(hexadecimal, 16);
} /**
* 按 /年/月日/小时 创建附件上传路径
*
* @return 附件上传路径
*/
public static String getFileDatePath() {
Calendar calendar = Calendar.getInstance();
int yearInt = calendar.get(Calendar.YEAR);
int monthInt = calendar.get(Calendar.MONTH) + 1;
int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
int hourInt = calendar.get(Calendar.HOUR_OF_DAY);
String monthStr = monthInt >= 10 ? String.valueOf(monthInt) : "0" + monthInt;
String dayStr = dayInt >= 10 ? String.valueOf(dayInt) : "0" + dayInt;
String hourStr = hourInt >= 10 ? String.valueOf(hourInt) : "0" + hourInt;
// 按 /年/月日/小时 创建附件上传路径
return SEPARATOR + yearInt + SEPARATOR + monthStr + dayStr + SEPARATOR + hourStr;
} /**
* 获取相应的地址
*
* @return 附件上传路径
*/
public static String getFilePath() {
Calendar calendar = Calendar.getInstance();
int yearInt = calendar.get(Calendar.YEAR);
int monthInt = calendar.get(Calendar.MONTH) + 1;
int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
int hourInt = calendar.get(Calendar.HOUR_OF_DAY);
String monthStr = monthInt >= 10 ? String.valueOf(monthInt) : "0" + monthInt;
String dayStr = dayInt >= 10 ? String.valueOf(dayInt) : "0" + dayInt;
String hourStr = hourInt >= 10 ? String.valueOf(hourInt) : "0" + hourInt;
// 按 /年/月日/小时 创建附件上传路径
return SEPARATOR + yearInt + SEPARATOR + monthStr + dayStr + SEPARATOR + hourStr;
} /**
* 从网络URL中下载文件
*
* @param urlStr
* 图片网络路径
* @param fileName
* 图片存储名称
* @param savePath
* 图片保存路径
* @throws IOException
* 异常
*/
public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
URL url;
// 得到输入流
InputStream inputStream = null;
FileOutputStream fos = null;
try {
url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
// 获取自己数组
byte[] getData = readInputStream(inputStream);
// 文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
fos = new FileOutputStream(file);
fos.write(getData);
} finally {
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
}
} /**
* 从输入流中获取字节数组
*
* @param inputStream
* 流
* @return byte数组
* @throws IOException
* 异常
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = null;
try {
byte[] buffer = new byte[1024];
int len = 0;
bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
} return bos.toByteArray();
} finally {
if (bos != null) {
bos.close();
}
}
} /**
* 生成小缩率图
*
* @param srcFilePath
* 原图路径
* @param thumbFilePath
* 缩率图路径
* @throws IOException
*/
private static void genSmallThumbPic(String srcFilePath, String thumbFilePath) throws IOException {
int width = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.APP_IMAGE_S_W);
int height = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.APP_IMAGE_S_H);
genThumbPic(srcFilePath, thumbFilePath, width, height);
} /**
* 生成中缩率图
*
* @param srcFilePath
* 原图路径
* @param thumbFilePath
* 缩率图路径
* @throws IOException
*/
private static void genMiddleThumbPic(String srcFilePath, String thumbFilePath) throws IOException {
int width = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.APP_IMAGE_M_W);
int height = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.APP_IMAGE_M_H);
genThumbPic(srcFilePath, thumbFilePath, width, height);
} /**
* 生成大缩率图
*
* @param srcFilePath
* 原图路径
* @param thumbFilePath
* 缩率图路径
* @throws IOException
*/
private static void genLargeThumbPic(String srcFilePath, String thumbFilePath) throws IOException {
int width = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.APP_IMAGE_L_W);
int height = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.APP_IMAGE_L_H);
genThumbPic(srcFilePath, thumbFilePath, width, height);
} /**
* 生成缩率图
*
* @param filePath
* 原图路径
* @param pathSuffix
* 文件名后缀
* @throws IOException
*/
private static void genThumbPic(String srcFilePath, String thumbFilePath, int width, int height)
throws IOException {
if (srcFilePath == null || srcFilePath.trim().length() == 0) {
return;
}
if (thumbFilePath == null || thumbFilePath.trim().length() == 0) {
return;
}
// 按指定大小把图片进行缩和放(会遵循原图高宽比例)
Thumbnails.of(new File(srcFilePath)).size(width, height).toFile(new File(thumbFilePath));
} /**
* 判断文件是否是图片
*
* @param fullFilePath
* 完整的文件路径
* @return String
*/
private static boolean isImage(String fileName) {
// 获取配置中支持的扩展名
String supportImageExts = AppPropPublicUtil.getPropValue(AppPropPublicUtil.Keys.APP_SUPPORT_IMAGE_EXT);
if (supportImageExts == null || supportImageExts.trim().length() == 0) {
return false;
}
// 获取配置中支持的扩展名
String fileExt = getFileExtension(fileName);
if (fileExt == null || fileExt.trim().length() == 0) {
return false;
}
return supportImageExts.toLowerCase().contains(fileExt.toLowerCase() + SEPARATOR);
} /**
* 测试获取网络图片到本地
*
* @param args
* 参数
*
*/
public static void main(String[] args) {
String path = "C:/Users/Administrator/Pictures/ab111.jpg";
System.out.println(isImage(path));
} /**
* 保存户型图
* @param ins 输入流
* @param fullFileName 全路径
* @param waterMakerPath 水印路径
* @return 相对路径
* @exception IOException 路径错误
*/
public static Map<String, String> uploadHousePic(InputStream ins, String fullFileName, String waterMakerPath) throws IOException {
if(StringUtils.isBlank(waterMakerPath)){
throw new IOException("户型图水印文件路径未配置,key为"+AppPropPublicUtil.Keys.APP_HOUSE_WATERMARKER);
}
Map<String, String> result = new HashMap<String, String>();
String fileSize = "0";
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
String relativePath = FILE_TYPE_UPLOAD + getFileDatePath();
// 完整文件名称
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(ins);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
fullFilePath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(fullFilePath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
fileSize = String.valueOf(f.length());
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
// 如果是图片,生成大中小图片
if (isImage(fullFileName)) { waterMarkHousePic(fullFilePath,null,waterMakerPath);
// 生成头像小图
genSmallThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.SMALL));
// 生成头像中图
genMiddleThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.MIDDLE));
waterMarkHousePic(genThubnFilePath(fullFilePath, ImageType.MIDDLE), genThubnFilePath(fullFilePath, ImageType.MIDDLE), waterMakerPath);
// 生成头像大图
genLargeThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.LARGE));
waterMarkHousePic(genThubnFilePath(fullFilePath, ImageType.LARGE), genThubnFilePath(fullFilePath, ImageType.LARGE), waterMakerPath);
}
// 大小
result.put(KEY_FILE_SIZE, fileSize);
// 相对路径
result.put(KEY_RELATIVE_PATH, relativePath + SEPARATOR + fullFileName); return result;
} /**
* 给户型图原图打水印
* @param fullFilePath 路径名
* @param waterMakerPath 水印路径印
* @return 打水印后的大图的路径
*/
private static String waterMarkHousePic(String fullFilePath,String targetPath, String waterMakerPath) throws IOException {
OutputStream os = null;
try {
File sourceFile = new File(fullFilePath);
Image srcImg = ImageIO.read(sourceFile); BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB); // 得到画笔对象
Graphics2D g = buffImg.createGraphics(); // 设置对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg
.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null); // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度 e
ImageIcon imgIcon = new ImageIcon(waterMakerPath); // 得到Image对象。
Image img = imgIcon.getImage(); float alpha =1f; // 透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha)); // 表示水印图片的位置
g.drawImage(img, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); if(StringUtils.isBlank(targetPath)){
targetPath =fullFilePath.substring(0, fullFilePath.lastIndexOf("."))+"_b"+fullFilePath.substring(fullFilePath.lastIndexOf(".")) ;
} os = new FileOutputStream(targetPath); // 生成图片
ImageIO.write(buffImg, "JPG", os); } finally {
try {
if (null != os)
os.close(); } catch (Exception e) {
e.printStackTrace();
}
}
return targetPath;
} /**
*
* @param ins 输入流
* @param fullFileName 文件名
* @param waterMakerPath 水印路径
* @return 信息
* @exception IOException 路径没找到
*/
public static Map<String, String> uploadPicWithWaterMarker(InputStream ins, String fullFileName,
String waterMakerPath) throws IOException {
if(StringUtils.isBlank(waterMakerPath)){
throw new IOException("一般图水印文件路径未配置,key为"+AppPropPublicUtil.Keys.APP_WATERMARKER);
}
Map<String, String> result = new HashMap<String, String>();
String fileSize = "0";
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
String relativePath = FILE_TYPE_UPLOAD + getFileDatePath();
// 完整文件名称
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(ins);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
fullFilePath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(fullFilePath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
fileSize = String.valueOf(f.length());
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
// 如果是图片,生成大中小图片
if (isImage(fullFileName)) { waterMarkPic(fullFilePath,null,waterMakerPath);
// 生成头像小图
genSmallThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.SMALL));
// 生成头像中图
genMiddleThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.MIDDLE));
waterMarkPic(genThubnFilePath(fullFilePath, ImageType.MIDDLE), genThubnFilePath(fullFilePath, ImageType.MIDDLE), waterMakerPath);
// 生成头像大图
genLargeThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.LARGE));
waterMarkPic(genThubnFilePath(fullFilePath, ImageType.LARGE), genThubnFilePath(fullFilePath, ImageType.LARGE), waterMakerPath);
}
// 大小
result.put(KEY_FILE_SIZE, fileSize);
// 相对路径
result.put(KEY_RELATIVE_PATH, relativePath + SEPARATOR + fullFileName); return result;
} private static String waterMarkPic(String fullFilePath,String targetPath ,String waterMakerPath) throws IOException {
OutputStream os = null;
try {
Image srcImg = ImageIO.read(new File(fullFilePath)); BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB); // 得到画笔对象
Graphics2D g = buffImg.createGraphics(); // 设置对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg
.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null); // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度 e
ImageIcon imgIcon = new ImageIcon(waterMakerPath); // 得到Image对象。
Image img = imgIcon.getImage(); float alpha =1f; // 透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha)); // 表示水印图片的位置
g.drawImage(img, (buffImg.getWidth()-img.getWidth(null))/2, (buffImg.getHeight()-img.getHeight(null))/2, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); if(StringUtils.isBlank(targetPath)){
targetPath =fullFilePath.substring(0, fullFilePath.lastIndexOf("."))+"_b"+fullFilePath.substring(fullFilePath.lastIndexOf(".")) ;
} os = new FileOutputStream(targetPath); // 生成图片
ImageIO.write(buffImg, "JPG", os); } catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return targetPath;
} /**
* @param inputStream 输入流
* @param fullFileName 文件名
* @return 信息
* @exception IOException 路径没找到
*/
public static Map<String, String> bannerUpload(InputStream inputStream, String fullFileName) throws IOException {
Map<String, String> result = new HashMap<String, String>();
String fileSize = "0";
BufferedInputStream in = null;
BufferedOutputStream out = null;
// 文件上传路径前缀
String basePath = AppPropUtil.getPropValue(AppPropUtil.Keys.FILE_UPLOAD_HTTP);
String relativePath = FILE_TYPE_UPLOAD + getFileDatePath();
// 完整文件名称
String fullFilePath = "";
// 返回上传附件信息
try {
// 获得文件输入流
in = new BufferedInputStream(inputStream);
// 文件的相对路径
File file = new File(basePath + relativePath);
// 若文件夹不存在,则递归创建文件夹
if (!file.exists()) {
file.mkdirs();
}
// 文件全路径
fullFilePath = basePath + relativePath + SEPARATOR + fullFileName;
File f = new File(fullFilePath);
// 获得文件输出流
out = new BufferedOutputStream(new FileOutputStream(f));
// 写入文件
Streams.copy(in, out, true);
fileSize = String.valueOf(f.length());
} finally {
try {
if (out != null) {
out.close();
}
} finally {
if (in != null) {
in.close();
}
}
}
// 如果是图片,生成大中小图片
if (isImage(fullFileName)) {
int width = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.BANNER_IMAGE_W);
int height = AppPropPublicUtil.getIntegerValue(AppPropPublicUtil.Keys.BANNER_IMAGE_H);
// 生成banner图
genThumbPic(fullFilePath, genThubnFilePath(fullFilePath, ImageType.BANNER), width, height);
}
// 大小
result.put(KEY_FILE_SIZE, fileSize);
// 相对路径
result.put(KEY_RELATIVE_PATH, relativePath + SEPARATOR + fullFileName); return result;
} }
5.app-config-dev.properties
#\u670d\u52a1\u5668\u8def\u5f84
APP_SERVER_PATH=http://172.16.5.66:8080/newhouse #\u8c03\u5ea6\u670d\u52a1\u5668\u8def\u5f84
SCHEDULE_SERVER_PATH=http://172.16.5.66:8080/newhouse #\u641c\u7d22\u5f15\u64ce\u5730\u5740
SEARCH_ES_SERVER=http://172.16.5.153:8083/EsQuery/query/
#SEARCH_ES_SERVER=http://127.0.0.1:8071/EsQuery/query/
SEARCH_ES_ClUSTER_NAME=maimai-es-test #\u6587\u4ef6\u4e0a\u4f20\u8def\u5f84\u524d\u7f00
FILE_UPLOAD_HTTP=/diskfile/system/httpsurl
FILE_UPLOAD_HTTPS=/diskfile/system/httpsurl
ANDROID_UPLOAD_PREFIX=/mobile/android
IOS_UPLOAD_PREFIX=/mobile/ios #\u8bfb\u53d6\u6587\u4ef6\u8def\u5f84\u524d\u7f00
DOWNLOAD_FILE_HTTP=http://192.168.183.47:8090/pic
DOWNLOAD_FILE_HTTPS=http://192.168.183.47:8090/pic
ANDROID_DEFAULT_INSTALL=https://mmdev1.maitian.cn/newhouse_100/default/newhouse.apk
IOS_DEFAULT_INSTALL=https://mmdev1.maitian.cn/newhouse_100/default/newhouse.plist #\u77ed\u4fe1\u76f8\u5173
SMS_URL=http://172.16.5.31:8000/api/sms
SMS_APPID=aadc9abe17f54007b5cca7a2513cb8b1
基于cxf的app文件上传接口(带回显功能)的更多相关文章
- 用c++开发基于tcp协议的文件上传功能
用c++开发基于tcp协议的文件上传功能 2005我正在一家游戏公司做程序员,当时一直在看<Windows网络编程> 这本书,把里面提到的每种IO模型都试了一次,强烈推荐学习网络编程的同学 ...
- 构建基于阿里云OSS文件上传服务
转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50710132 <构建基于阿里云OSS文件上传服务> <构建基于OS ...
- springmvc图片文件上传接口
springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...
- Servlet3.0学习总结——基于Servlet3.0的文件上传
Servlet3.0学习总结(三)——基于Servlet3.0的文件上传 在Servlet2.5中,我们要实现文件上传功能时,一般都需要借助第三方开源组件,例如Apache的commons-fileu ...
- Struts2文件上传(基于表单的文件上传)
•Commons-FileUpload组件 –Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目 •Commons-Fil ...
- [原创]java WEB学习笔记49:文件上传基础,基于表单的文件上传,使用fileuoload 组件
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- jmeter测试文件上传接口报错:connection reset by peer: socket write error
最近在对文件上传接口性能测试时,设置150线程数并发时,总会出现以下错误:connection reset by peer: socket write error 在网上搜索了一下,得到的原因有这些: ...
- Python 基于Python实现Ftp文件上传,下载
基于Python实现Ftp文件上传,下载 by:授客 QQ:1033553122 测试环境: Ftp客户端:Windows平台 Ftp服务器:Linux平台 Python版本:Python 2.7 ...
- FastDFS的配置、部署与API使用解读(8)FastDFS多种文件上传接口详解(转)
1.StorageClient与StorageClient1的区别 相信使用happy_fish的FastDFS的童鞋们,一定都熟悉StorageClient了,或者你熟悉的是StorageClien ...
随机推荐
- rockchip 3128 平台USB接口鼠标U盘功能调试日记
2019-04-12 关键词: rk3128 OTG.rk3128外接鼠标U盘.RK外接鼠标U盘 本篇文章是笔者根据自己当前所掌握知识对 rk3128 平台 USB 接口接鼠标实现输入功能调试的一个记 ...
- 差分约束 HDU - 1384 HDU - 3592 HDU - 1531 HDU - 3666
Intervals Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...
- 使用diff或者vimdiff比较远程文件(夹)与本地文件夹
方法1:管道给diff $ssh eric@192.168.1.11 "cat ~/remote_file.txt" | diff - ~/local_file.txt 如果 Fi ...
- [HNOI2009]最小圈(分数规划+SPFA判负环)
题解:求环长比环边个数的最小值,即求min{Σw[i]/|S|},其中i∈S.这题一眼二分,然后可以把边的个数进行转化,假设存在Σw[i]/|S|<=k,则Σw[i]-k|S|<=0,即Σ ...
- Java:IO流-流的操作规律和转换流
首先我们先来了解一些IO流基本知识. 一,基本知识概括 具体的IO流有很多种,针对不同的应用场景应该使用相应的流对象.但怎么确定应该使用哪个IO流对象呢? 一般要有四个明确: 1)明确源和目的 源:I ...
- idea 排除编译 参考
参考自 : https://www.bbsmax.com/A/LPdoYLkGJ3/
- JS中如何获取JSON有多少个字段,JSON子项的个数或叫length
如有JSON数据格式如下: {names:'张三','age':16,'sex':‘男’} 或 {names:'张三','age':16,'sex':‘男’} 如何获取JSON子键的数量?挺头疼的.使 ...
- js手写'Promise'
/* * pending:初始化成功 * fulfilled:成功 * rejected:失败 * */ function Promise(executor) {// 执行器 this.status ...
- JSP和后台交互时的乱码问题
在Servlet或者是拦截器里面添加下面的语句: request.setCharacterEncoding("utf-8"); response.setCharacterEncod ...
- selenium中的下拉框处理模块Select
在UI自动化测试过程中,经常会遇到一些下拉框,如果我们基于Webdriver操作的话就需要click两次,而且很容易出现问题,实际上Selenium给我们提供了专门的Select(下拉框处理模块). ...