Commit cc1f9913 authored by yangshuxing's avatar yangshuxing

项目初始化

parents
Pipeline #138 failed with stages
<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.neusoft.upload</groupId>
<artifactId>rmiupload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.spring>4.0.7.RELEASE</version.spring>
<jackson.version>2.4.1.1</jackson.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${version.spring}</version>
</dependency>
<!-- end spring 核心依赖包 -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2.2</version>
</dependency>
<!-- start spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk13</classifier>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>${project.build.sourceEncoding}</encoding>
<failOnError>false</failOnError>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<!-- mybatis xml文件maven打包进相应class目录 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
<packaging>war</packaging>
</project>
\ No newline at end of file
package com.neusoft.upload.httpclient;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.neusoft.upload.service.RMIUpload;
import com.neusoft.upload.util.ResponseJSON;
@Controller
@RequestMapping("/httpUpload")
public class HttpUploadController {
@Autowired
private RMIUpload rmiUpload;
@RequestMapping("/uploadByAjax.do")
public String uploadByAjax(HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject resultJson = new JSONObject();
String uploadFileId = request.getParameter("uploadFileId");
String uploadPath = request.getParameter("uploadPath");
// 上传路径必须
if (StringUtils.isBlank(uploadPath)) {
resultJson.put("status", -1);
resultJson.put("message", "upload path is null");
ResponseJSON.writeAndSetUTF8(response, resultJson);
return null;
}
// 上传文件必须
if (StringUtils.isBlank(uploadFileId)) {
resultJson.put("status", -1);
resultJson.put("message", "upload file is null");
ResponseJSON.writeAndSetUTF8(response, resultJson);
return null;
}
try {
// 转型为MultipartHttpRequest(重点的所在)
// 增加赛事如果有图片提交过来 转换request为MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得第1张图片(根据前台的name名称得到上传的文件)
MultipartFile multipartFile = multipartRequest.getFile(uploadFileId);
if (null != multipartFile && !multipartFile.isEmpty()) {
CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
String fileName = fi.getName();
Map<String, String> result = rmiUpload.uploadFile(multipartFile.getBytes(), fileName, uploadPath);
if (null != result) {
resultJson = JSONObject.fromObject(result);
resultJson.put("status", 0);
resultJson.put("message", "upload success");
} else {
resultJson.put("status", -1);
resultJson.put("message", "upload failure");
}
}
} catch (ClassCastException caseEx) {
caseEx.printStackTrace();
resultJson.put("status", -1);
resultJson.put("message", "upload file format error, need to give me MultipartFile");
} catch (Exception e) {
e.printStackTrace();
resultJson.put("status", -1);
resultJson.put("message", "error, error message : " + e.getMessage());
}
ResponseJSON.writeAndSetUTF8(response, resultJson);
return null;
}
@RequestMapping("/uploadByHttpClient.do")
public String uploadByHttpClient(HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject resultJson = new JSONObject();
String uploadPath = request.getParameter("uploadPath");
// 上传路径必须
if (StringUtils.isBlank(uploadPath)) {
resultJson.put("status", -1);
resultJson.put("message", "upload path is null");
ResponseJSON.writeAndSetUTF8(response, resultJson);
return null;
}
try {
// 转型为MultipartHttpRequest(重点的所在)
// 增加赛事如果有图片提交过来 转换request为MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得第1张图片(根据前台的name名称得到上传的文件)
MultipartFile multipartFile = null;
// multipartRequest.getFile(uploadFileId);
Map<String, MultipartFile> mfMap = multipartRequest.getFileMap();
if (null != mfMap) {
for (String key : mfMap.keySet()) {
multipartFile = mfMap.get(key);
if (null != multipartFile) {
break;
}
}
}
if (null != multipartFile && !multipartFile.isEmpty()) {
CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
String fileName = fi.getName();
Map<String, String> result = rmiUpload.uploadFile(multipartFile.getBytes(), fileName, uploadPath);
if (null != result) {
resultJson = JSONObject.fromObject(result);
resultJson.put("status", 0);
resultJson.put("message", "upload success");
} else {
resultJson.put("status", -1);
resultJson.put("message", "upload failure");
}
}
} catch (ClassCastException caseEx) {
caseEx.printStackTrace();
resultJson.put("status", -1);
resultJson.put("message", "upload file format error, need to give me MultipartFile");
} catch (Exception e) {
e.printStackTrace();
resultJson.put("status", -1);
resultJson.put("message", "error, error message : " + e.getMessage());
}
ResponseJSON.writeAndSetUTF8(response, resultJson);
return null;
}
}
package com.neusoft.upload.service;
import java.rmi.Remote;
import java.util.Map;
public interface RMIUpload extends Remote {
public String upload(String param) throws Exception;
/**
*
* @param multipartFile
* 提交过来的文件流
* @param storagePath
* 存储路径
* @return 返回一个字符串(存储路径+文件名)
* @throws Exception
*/
public Map<String, String> uploadFile(byte[] fileBytes, String fileName, String storagePath) throws Exception;
/**
*
* @param fileBytes 提交过来的文件流
* @param fileName 文件名字
* @param storagePath 存储路径
* @return 返回一个字符串(存储路径+文件名)
* @throws Exception
*/
public Map<String,String> uploadOSSFile(byte[] fileBytes,String fileName,String storagePath) throws Exception;
}
package com.neusoft.upload.service.impl;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import com.neusoft.upload.service.RMIUpload;
import com.neusoft.upload.util.OSSClientUtil;
import com.neusoft.upload.util.SystemConfig;
@Service("rmiUpload")
public class RMIUploadImpl extends UnicastRemoteObject implements RMIUpload {
private static Logger logger = Logger.getLogger(RMIUploadImpl.class);
private static final long serialVersionUID = 1L;
public RMIUploadImpl() throws java.rmi.RemoteException {
super();
}
public void initialRmi() {
try {
RMIUpload rmi = new RMIUploadImpl();
String rmiServerHost = SystemConfig.getProperty("rmi.server.host");
int rmiServerPort = SystemConfig.getIntProperty("rmi.server.port", 9125);
String rmiServerServiceName = SystemConfig.getProperty("rmi.server.servicename", "RMIUpload");
String rmiServerUrl = "rmi://" + rmiServerHost + ":" + rmiServerPort + "/" + rmiServerServiceName;
// 注册通讯端口
LocateRegistry.createRegistry(rmiServerPort);
// 注册通讯路径
Naming.rebind(rmiServerUrl, rmi);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
public String upload(String param) throws Exception {
System.out.println(param);
return param;
}
/**
* 文件上传操作
*
* @param storagePath
* 文件存放的相对路径
* @param fileBytes
* 文件字节流
* @param fileName
* 文件名
* @return
* @throws FileNotFoundException
* @throws IOException
*/
@Override
public Map<String, String> uploadFile(byte[] fileBytes, String fileName, String storagePath) throws FileNotFoundException, IOException {
Map<String, String> result = new HashMap<String, String>();
String rootPath = SystemConfig.getProperty("upload.path.root", "/home/nginx/geexek_nginx_data/");
String newFileName = modifyFileNameByUUID(fileName);
// 文件的父目录 如果不存在 自动补充创建
File file = new File(rootPath + storagePath);
if (!file.exists()) {
file.mkdirs();
}
// 文件上传的绝对路径
String fileAbsolutepath = rootPath + storagePath + newFileName;
// 文件读写
OutputStream ostream = new FileOutputStream(fileAbsolutepath);
ostream.write(fileBytes);
ostream.flush();
ostream.close();
String fileRelativePath = storagePath + newFileName;
result.put("fileRelativePath", fileRelativePath);
String fileSuffix = "";
// 获取文件后缀名
if (StringUtils.isBlank(fileName) || fileName.indexOf(".") != -1) {
fileSuffix = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
}
// 如果是图片需要进行压缩
if (fileIsImage(fileSuffix)) {
int newWidth = SystemConfig.getIntProperty("image.upload.compress.width", 120);
int newHeight = SystemConfig.getIntProperty("image.upload.compress.height", 120);
byte[] resultBytes = compress(fileBytes, newWidth, newHeight, fileSuffix);
String newFileName_c = modifyFileNameByUUID(fileName);
// 文件上传的绝对路径
String fileAbsolutepath_c = rootPath + storagePath + newFileName_c;
OutputStream ostream_c = new FileOutputStream(fileAbsolutepath_c);
ostream_c.write(resultBytes);
ostream_c.flush();
ostream_c.close();
// 压缩后的图片存放路径
String fileRelativePath_c = storagePath + newFileName_c;
result.put("fileRelativePath_c", fileRelativePath_c);
}
return result;
}
/**
* 根据文件后缀名判断是否是图片
*
* @param fileName
* 文件名
* @return
*/
private boolean fileIsImage(String fileSuffix) {
if (StringUtils.isBlank(fileSuffix)) {
return false;
}
// 声明图片后缀名数组
String imgeArray[] = { "bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tiff" };
// 遍历名称数组
for (int i = 0; i < imgeArray.length; i++) {
// 判断单个类型文件的场合
if (imgeArray[i].equals(fileSuffix)) {
return true;
}
}
return false;
}
/**
* 使用uuid修改文件名称
*
* @param fileName
* 文件名称
* @return
*/
private String modifyFileNameByUUID(String fileName) {
String fileNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
UUID uuid = UUID.randomUUID();
return uuid.toString() + "." + fileNameSuffix;
}
/**
*
* 根据指定的宽高压缩图片文件 并返回处理过后的字节数组
*
* @param newWidth
* 图片新的宽度
* @param newHeight
* 图片新的高度
* @param formatName
* 图片格式 一般保留图片源格式 即原有后缀
* @return 字节数组
* @throws IOException
*/
public byte[] compress(byte[] fileBytes, int newWidth, int newHeight, String formatName) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream buffin = new ByteArrayInputStream(fileBytes);
// 构造Image对象
Image image = ImageIO.read(buffin);
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
int targetWidth, targetHeight;
if (imageWidth < newWidth && imageHeight < newHeight) {
targetWidth = imageWidth;
targetHeight = imageHeight;
} else if (imageWidth * newHeight > imageHeight * newWidth) {
targetWidth = newWidth;
targetHeight = imageHeight * newWidth / imageWidth;
} else if (imageWidth * newHeight < imageHeight * newWidth) {
targetWidth = imageWidth * newHeight / imageHeight;
targetHeight = newHeight;
} else {
targetWidth = newWidth;
targetHeight = newHeight;
}
BufferedImage bi = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.clearRect(0, 0, targetWidth, targetHeight);
g.setColor(Color.white);
g.fillRect(0, 0, targetWidth, targetHeight);
g.drawImage(image, 0, 0, targetWidth, targetHeight, null);
ImageIO.write(bi, formatName, baos);
baos.flush();
return baos.toByteArray();
}
@Override
public Map<String, String> uploadOSSFile(byte[] fileBytes, String fileName,String storagePath){
logger.info(fileName+"==="+storagePath);
Map<String, String> result = new HashMap<String, String>();
String newFileName = modifyFileNameByUUID(fileName);
InputStream buffin = new ByteArrayInputStream(fileBytes);
try{
String ret=OSSClientUtil.uploadFile2OSS(buffin, storagePath, newFileName);
result.put("fileRelativePath", ret);
result.put("fileRelativePath_c", ret+"?x-oss-process=image/resize,w_100");
}catch(Exception e){
logger.error("错误"+e);
e.printStackTrace();
}
logger.info(fileName+"==="+storagePath);
return result;
}
public static void main(String[] args) {
File f=new File("D:\\1509947539158.jpg");
try {
long start=System.currentTimeMillis();
for(int i=0;i<100;i++){
byte[] fileBytes=getByte(f);
RMIUploadImpl rmi=new RMIUploadImpl();
Map<String,String> res=new HashMap<String,String>();
res=rmi.uploadOSSFile(fileBytes,"1509947539158.jpg","run/cmpt/images/2017/12/07/");
System.out.println(res.get("fileRelativePath"));
}
long end=System.currentTimeMillis();
System.out.println((start-end)/1000+"秒");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] getByte(File file) throws Exception
{
byte[] bytes = null;
if(file!=null)
{
InputStream is = new FileInputStream(file);
int length = (int) file.length();
if(length>Integer.MAX_VALUE) //当文件的长度超过了int的最大值
{
System.out.println("this file is max ");
return null;
}
bytes = new byte[length];
int offset = 0;
int numRead = 0;
while(offset<bytes.length&&(numRead=is.read(bytes,offset,bytes.length-offset))>=0)
{
offset+=numRead;
}
//如果得到的字节长度和file实际的长度不一致就可能出错了
if(offset<bytes.length)
{
System.out.println("file length is error");
return null;
}
is.close();
}
return bytes;
}
}
package com.neusoft.upload.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
/**
* 阿里云的OSS存储方法
* @author sunyuhua
*
*2017年12月7日下午6:20:57
*
*/
public class OSSClientUtil {
// 阿里云API的内或外网域名
private static String ENDPOINT = "oss-cn-hangzhou-internal.aliyuncs.com";
// 阿里云API的密钥Access Key ID
private static String ACCESS_KEY_ID = "LTAI9x2WCRZ9l8lv";
// 阿里云API的密钥Access Key Secret
private static String ACCESS_KEY_SECRET = "zs6LsezxNXIkx6GVKG4qtx4EXFsMmz";
// 图片cdn访问路径
private static String PHOTOHTTP = "http://imgoss.geexek.com/";
// 空间
public static String BUCKET_NAME = "geexekimgoss";
private static Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
/**
* 获取阿里云OSS客户端对象
*/
public static final OSSClient getOSSClient() {
ClientConfiguration conf = new ClientConfiguration();
conf.setMaxConnections(100); // 设置HTTP最大连接数为10
conf.setConnectionTimeout(5000); // 设置TCP连接超时为5000毫秒
conf.setMaxErrorRetry(3); // 设置最大的重试次数为3
conf.setSocketTimeout(5000); // 设置Socket传输数据超时的时间为5000毫秒
return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET, conf);
}
/**
* 单独创建文件夹 Create an empty folder without request body, note that the key must be suffixed with a slash
*
* @param keySuffixWithSlash 文件夹的路径
* @return 返回文件夹的路径
* @throws Exception
*/
public static String CreateObject(String keySuffixWithSlash) throws Exception {
OSSClient client = getOSSClient();
client.putObject(BUCKET_NAME, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
OSSObject object = client.getObject(BUCKET_NAME, keySuffixWithSlash);
String objectName = object.getKey();
object.getObjectContent().close();
client.shutdown();
return objectName;
}
/**
* 批量删除文件 Delete all objects uploaded recently under the bucket
*
* @param keys 文件路径
* @return
* @throws Exception
*/
public static List<String> DeleteObjects(List<String> keys) throws Exception {
OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
DeleteObjectsResult deleteObjectsResult = client.deleteObjects(new DeleteObjectsRequest(BUCKET_NAME).withKeys(keys));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
client.shutdown();
return deletedObjects;
}
/**
* 单个删除文件夹,文件中有其他文件,将不能删除,需先删除底层的文件才行
*
* @param key
* @return
* @throws Exception
*/
public static boolean DeleteObjects(String key) throws Exception {
OSSClient client = getOSSClient();
client.deleteObject(BUCKET_NAME, key);
return true;
}
/**
* 断点续传单张图片
*
* @param key
* @param fileurl
* @return
* @throws Throwable
*/
public static String UploadFile(String key, String fileurl) throws Throwable {
OSSClient client = getOSSClient();
UploadFileRequest uploadFileRequest = new UploadFileRequest(BUCKET_NAME, key);
// 指定上传的本地文件
uploadFileRequest.setUploadFile(fileurl);
// 指定上传并发线程数
uploadFileRequest.setTaskNum(5);
// 指定上传的分片大小
uploadFileRequest.setPartSize(1 * 1024 * 1024);
// 开启断点续传
uploadFileRequest.setEnableCheckpoint(true);
// 断点续传上传
UploadFileResult ufr = client.uploadFile(uploadFileRequest);
// 关闭client
client.shutdown();
logger.info(ufr.getMultipartUploadResult().getLocation());
return ufr.getMultipartUploadResult().getLocation();
}
/**
* 上传到OSS服务器 如果同名文件会覆盖OSS
*
* @param instream 文件流
* @param filedir 文件存储的文件夹
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
* @throws Exception
*/
public static String uploadFile2OSS(InputStream instream, String filedir, String fileName) throws Exception {
String ret = "";
OSSClient client = getOSSClient();
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
String type = getcontentType(fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()));
objectMetadata.setContentType(type);
objectMetadata.setContentDisposition("inline;filename=" + fileName);
PutObjectResult putResult = client.putObject(BUCKET_NAME, filedir + fileName, instream, objectMetadata);
ret = putResult.getETag();
String fileOSSUrl = "";
if (ret != null) {
fileOSSUrl = PHOTOHTTP + filedir + fileName;
}
logger.info("aliyun img" + fileOSSUrl);
instream.close();
client.shutdown();
return fileOSSUrl;
}
/**
* 根据key获取OSS服务器上的文件输入流
*
* @param diskName 文件路径
* @param key Bucket下的文件的路径名+文件名
*/
public static final InputStream getOSS2InputStream(String filedir, String fileName) throws Exception {
OSSClient client = getOSSClient();
OSSObject ossObj = client.getObject(BUCKET_NAME, fileName);
client.shutdown();
return ossObj.getObjectContent();
}
/**
* 根据key删除OSS服务器上的文件
*
* @param fileName 文件的路径名+文件名
* @return 删除标示
* @throws Exception
*/
public static boolean deleteFile(String fileName) throws Exception {
OSSClient client = getOSSClient();
client.deleteObject(BUCKET_NAME, fileName);
return true;
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public static String getOSSFileUrl(String fileUrl, String filedir) {
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return getUrl(filedir + split[split.length - 1]);
}
return null;
}
/**
* 获得url链接
*
* @param key
* @return
*/
public static String getUrl(String key) {
OSSClient client = getOSSClient();
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = client.generatePresignedUrl(BUCKET_NAME, key, expiration);
client.shutdown();
if (url != null) {
return url.toString();
}
return null;
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param extention 文件后缀
* @return String
*/
public static String getcontentType(String extention) {
logger.info("后缀"+extention);
System.out.println(extention);
if (extention.equalsIgnoreCase("bmp")) {
return "image/bmp";
}
if (extention.equalsIgnoreCase("gif")) {
return "image/gif";
}
if (extention.equalsIgnoreCase("jpeg") ||
extention.equalsIgnoreCase("jpg") ||
extention.equalsIgnoreCase("png")) {
return "image/jpeg";
}
if (extention.equalsIgnoreCase("html")) {
return "text/html";
}
if (extention.equalsIgnoreCase("txt")) {
return "text/plain";
}
if (extention.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
}
if (extention.equalsIgnoreCase("pptx") ||
extention.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
}
if (extention.equalsIgnoreCase("docx") ||
extention.equalsIgnoreCase("doc")) {
return "application/msword";
}
if (extention.equalsIgnoreCase("xml")) {
return "text/xml";
}
if (extention.equalsIgnoreCase("xls") ||
extention.equalsIgnoreCase("xlsx")) {
return "application/vnd.ms-excel";
}
if (extention.equalsIgnoreCase("pdf")) {
return "application/pdf";
}
return "image/jpeg";
}
/**
* 新建Bucket --Bucket权限:私有
*
* @param bucketName bucket名称
* @return true 新建Bucket成功
*/
public static final boolean createBucket(OSSClient client, String bucketName) {
Bucket bucket = client.createBucket(bucketName);
return bucketName.equals(bucket.getName());
}
/**
* 删除Bucket
*
* @param bucketName bucket名称
**/
public static final void deleteBucket(OSSClient client, String bucketName) {
client.deleteBucket(bucketName);
}
/**
* 根据key删除OSS服务器上的文件
*
* @param client OSS客户端
* @param bucketName bucket名称
* @param diskName 文件路径
* @param key Bucket下的文件的路径名+文件名
*/
public static void deleteFile(OSSClient client, String bucketName, String diskName, String key) {
client.deleteObject(bucketName, diskName + key);
}
}
package com.neusoft.upload.util;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class ResponseJSON {
public static void writeJSsonAndSetUTF8(HttpServletResponse response, JSONObject object) {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(object.toString());
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
public static void writeAndSetUTF8(HttpServletResponse response, Object object) {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(object.toString());
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
package com.neusoft.upload.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring容器的工具类 可由此获取ApplicationContext
*
* @author wang-zh.neu
*
*/
public class SpringContextHolder implements ApplicationContextAware {
/**
* 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.
*/
private static ApplicationContext context;
/**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
public void setApplicationContext(ApplicationContext context) {
SpringContextHolder.context = context;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
package com.neusoft.upload.util;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
/**
*
*
* @author wang-zh.neu
*
*/
public final class SystemConfig implements InitializingBean {
/**
* 配置文件属性键值对
*/
private static Map<String, String> systemProperties = new HashMap<String, String>();
// 资源文件位置
private String[] propertiesLocation;
public String[] getPropertiesLocation() {
return propertiesLocation;
}
public void setPropertiesLocation(String[] propertiesLocation) {
this.propertiesLocation = propertiesLocation;
}
/**
* 根据key获取value
*
* @param key
* @return
*/
public static String getProperty(final String key) {
return systemProperties.get(key);
}
/**
* 根据key获取value
*
* @param key
* @return
*/
public static String getTrimProperty(final String key) {
return StringUtils.trimToEmpty((String) systemProperties.get(key));
}
/**
* 根据key获取value,获取为空则返回默认值
*
* @param key
* @param defaultString
* @return
*/
public static String getProperty(final String key, final String defaultString) {
String prop = getProperty(key);
return StringUtils.isBlank(prop) ? defaultString : prop;
}
/**
* 根据key获取Integer类型的value
*
* @param key
* 参数名称.
* @return 参数值.
*/
public static int getIntProperty(final String key) {
return getIntProperty(key, 0);
}
/**
* 根据key获取Integer类型的value,获取为空则返回默认值
*
* @param key
* 参数名称.
* @param defaultValue
* 默认值.
* @return 参数值.
*/
public static int getIntProperty(final String key, int defaultValue) {
String property = StringUtils.trimToNull(getProperty(key));
if (property == null)
return defaultValue;
int value;
try {
value = Integer.parseInt(property);
} catch (NumberFormatException e) {
value = defaultValue;
}
return value;
}
/**
* 根据key获取Long类型的value,获取为空则返回默认值
*
* @param key
* 参数名称.
* @param defaultValue
* 默认值.
* @return 参数值.
*/
public static long getLongProperty(final String key, long defaultValue) {
String property = StringUtils.trimToNull(getProperty(key));
if (property == null) {
return defaultValue;
}
long value;
try {
value = Long.parseLong(property);
} catch (NumberFormatException e) {
value = defaultValue;
}
return value;
}
/**
* 获取配置文件中的整型参数值.
*
* @param key
* 参数名称.
* @return 整型参数值.
*/
public static Integer getIntegerProperty(final String key) {
return getIntegerProperty(key, null);
}
/**
* 获取配置文件中的整型参数值.
*
* @param key
* 参数名称.
* @param defaultValue
* 缺省值.
* @return 整型参数值.
*/
public static Integer getIntegerProperty(final String key, final Integer defaultValue) {
String strVal = StringUtils.trimToNull(getProperty(key));
Integer value = defaultValue;
if (strVal != null) {
try {
value = Integer.parseInt(strVal);
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* 获取配置文件中的布尔参数值.
*
* @param key
* 参数名称.
* @return 布尔参数值.
*/
public static boolean getBooleanProperty(final String key) {
return getBooleanProperty(key, false);
}
/**
* 获取配置文件中的布尔参数.如果文件中没有该参数就返回defaultValue.
*
* @param key
* 参数名称.
* @param defaultValue
* 参数默认值.
* @return 布尔参数值.
*/
public static boolean getBooleanProperty(final String key, final boolean defaultValue) {
if (systemProperties == null) {
return defaultValue;
}
Object value = systemProperties.get(key);
if (null != value) {
String strValue = StringUtils.trimToNull(value.toString());
return "true".equalsIgnoreCase(strValue) || "on".equalsIgnoreCase(strValue) || "yes".equalsIgnoreCase(strValue) || "1".equalsIgnoreCase(strValue);
} else {
return defaultValue;
}
}
/**
* 默认获取classpath下config文件中所有的properties文件
*
* @throws Exception
*/
public void afterPropertiesSet() throws Exception {
if (null == systemProperties) {
systemProperties = new HashMap<String, String>();
}
if (null != propertiesLocation && propertiesLocation.length > 0) {
for (String filePath : propertiesLocation) {
InputStream inStream = this.getClass().getResourceAsStream("/" + filePath);
if (null == inStream) {
continue;
}
Properties prop = new Properties(); // 实例化
prop.load(inStream);
// 返回Properties中包含的key-value的Set视图
Set<Entry<Object, Object>> set = prop.entrySet();
// 返回在此Set中的元素上进行迭代的迭代器
Iterator<Map.Entry<Object, Object>> it = set.iterator();
String key = null, value = null;
// 循环取出key-value
while (it.hasNext()) {
Entry<Object, Object> entry = it.next();
key = String.valueOf(entry.getKey());
value = String.valueOf(entry.getValue());
if (StringUtils.isNotBlank(key)) {
value = StringUtils.isNotBlank(value) ? value : "";
systemProperties.put(key, value);
}
}
}
}
}
}
#rmi.server.host=10.22.19.155
rmi.server.host=127.0.0.1
rmi.server.port=9125
rmi.server.servicename=RMIUpload
image.upload.compress.width=120
image.upload.compress.height=120
### \u8BBE\u7F6E###
log4j.rootLogger=INFO,stdout,D,E
### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### \u8F93\u51FADEBUG \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=D://logs/debug.log ###
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.Threshold=INFO
log4j.appender.D.File=../logs/rmi
log4j.appender.D.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### \u8F93\u51FAERROR \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=D://logs/error.log ###
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File=../logs/error
log4j.appender.E.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.E.Threshold=ERROR
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
\ No newline at end of file
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/tx/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:context-param.properties" ignore-unresolvable="true" />
<!-- 注解扫描 -->
<context:component-scan base-package="com.neusoft.upload" />
<context:annotation-config />
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上传文件的总大小不能超过20MB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="20000000"/>
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/index.html页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">upload_error.html</prop>
</props>
</property>
</bean>
<!-- Spring工具类 Spring初始化时自动将ApplicationContext注入到SpringContextHolder属性中去 -->
<bean class="com.neusoft.upload.util.SpringContextHolder" />
<!-- 读取配置文件工具类 属性中放置classpath资源文件路径(相对路径) -->
<bean id="systemConfig" class="com.neusoft.upload.util.SystemConfig">
<property name="propertiesLocation">
<list>
<value>upload-rmi-server.properties</value>
<value>context-param.properties</value>
</list>
</property>
</bean>
<bean id="rmiUpload" class="com.neusoft.upload.service.impl.RMIUploadImpl" init-method="initialRmi" depends-on="systemConfig"/>
</beans>
\ No newline at end of file
###windows develop\u5f00\u53d1\u73af\u5883\u8c03\u8bd5
#upload.path.root=D:/tools/nginx-1.7.9/html/
###linux production\u751f\u4ea7\u73af\u5883
upload.path.root=/geexek/nginx/nginx_data/
oss.key=LTAI9x2WCRZ9l8lv
oss.secret=zs6LsezxNXIkx6GVKG4qtx4EXFsMmz
oss.endpoint=http://oss-cn-hangzhou.aliyuncs.com
#oss.endpoint=oss-cn-hangzhou-internal.aliyuncs.com
oss.url=http://imgoss.geexek.com/
oss.backet=geexekimgoss
\ No newline at end of file
Manifest-Version: 1.0
Class-Path:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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">
<display-name>rmiupload</display-name>
<context-param>
<!-- 日志配置文件路径 -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<context-param>
<!-- 日志页面的刷新间隔 -->
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>rmi-upload</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:rmi_server_context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>rmi-upload</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment