⽂件上传⽰例(上传到amazons3服务器)
⽂件上传⽰例(上传到amazon s3服务器)
action调⽤上传⼯具类
@Action(value = "files-upload",
results = {@Result(name = SUCCESS, location = COMMON_PAGES_ROOT + "/noData.jsp")})
public String filesUpload() {
try {
// ⽣成的临时⽂件
baseLog.info("===start to upload:"+Name());
......
if (StringUtils.isEmpty(upload(FILE_ACTION_URL))) {
setStatus(ERROR_CODE_SYSTEM);
return SUCCESS;
}
JSONArray array = JSONArray.fromObject(upload(FILE_ACTION_URL));
List<TwitterFile> allFiles = new ArrayList<>();
for (Object o : array) {
JSONObject json = JSONObject.fromObject(o);
if (json != null) {
TwitterFile allFile = jsonToFiles(json.optString("url"), uploadFile.length());
allFiles.add(allFile);
break;
}
}
......
FILE_ACTION_URL 是本地临时存放的相对路径,如: FILE_ACTION_URL= /upload/file
upload⽅法
//上传到服务器-》上传到s3
private String upload(String url) throws NameServiceException { // url=/upload/file
baseLog.info("file name =" + uploadFileName + ", contentType=" + uploadContentType);
NameService nameService = Instance().getNameService();
StringBuilder sb = new StringBuilder();
sb.Host(UPLOAD_SERVICE_NAME)).append(url); // sb=192.168.0.121:8011/file-upload/upload/file
baseLog.info("================> " + sb.toString()); // ================> 192.168.0.121:8011/file-upload/upload/file
Map<String, String> params = new HashMap<String, String>(1);
params.put(FileUploader.PRI_PATH_REQUEST_PARAM_KEY, String()); //查询条件参数
String uploadResponse = new String()).upload(uploadFileName, uploadContentType, uploadFile, params);
/** FileUploader⼯具类上传⽂件到
s3⽂件 [{"name":"通讯录拼⾳处理⽅式.txt","url":"devrs.s3-north-1.amazonaws/12228/2017/05/13/451027d0-22f0-446e-99bd-a6753 baseLog.info("Response ================> " + uploadResponse);
return uploadResponse;
replaceall()}
⼯具类上传s3
public class FileUploader {
private static final Logger LOG = Logger(FileUploader.class);
private static final int CONNECTION_TIMEOUT_FIRST = 5000;
private static final int CONNECTION_TIMEOUT_SECOND = 50000;
private static final String REMOVE_REQUEST_PARAM_KEY = "rm";
public static final String PRI_PATH_REQUEST_PARAM_KEY = "pripath";
private static final String FILE_ACTION_URL = "/upload/file";
private static final String IMAGE_ACTION_URL = "/upload/image";
private static final String ICON_ACTION_URL = "/upload/icon";
private static final String ICON_ACTION_URL = "/upload/icon";
/
**
* 上传的servlet url
*/
private final String uploadServlet;
public String getUploadServlet() {
return uploadServlet;
}
public FileUploader(String uploadServlet) {
this.uploadServlet = uploadServlet;
}
/**
* 上传⽂件
*
* @param fileName ⽂件名
* @param fileContentType ⽂件content type
* @param file 要上传的⽂件
* @param requestParams 请求参数
* @return上传后的返回响应
*/
public String upload(String fileName, String fileContentType, File file, Map<String, String> requestParams) {
String resp = "";
//使⽤Local⽂件系统时
if(FileUploaderUtil.isLocal()){
Part[] parts = null;
final HttpClient client = Instance().createHttpClient();
final PostMethod filePost = new PostMethod(uploadServlet);
try {
if (requestParams != null && !requestParams.isEmpty()) {
parts = new Part[requestParams.size() + 1];
int index = 0;
for (Map.Entry<String, String> entry : Set()) {
Key().equalsIgnoreCase(PRI_PATH_REQUEST_PARAM_KEY)){
parts[index] = new Key(), Value().replaceAll("\\.","_"));
}else {
parts[index] = new Key(), Value());
}
index++;
}
}
parts[parts.length - 1] = new FilePart(fileName, fileName, file, fileContentType, "UTF-8");
filePost.setRequestEntity(new MultipartRequestEntity(parts, Params()));
int status = uteMethod(filePost);
LOG.info("http client execute status : " + status);
if (status == HttpStatus.SC_OK) {
LOG.debug("上传成功");
resp = ResponseBodyAsString();
} else {
LOG.warn("上传失败,重新试⼀次。。。");
if (status == HttpStatus.SC_OK)
resp = ResponseBodyAsString();
}
} catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
//TODO
} finally {
}
}else {
//使⽤local⽂件系统以外时
short fileType = 0;
dsWith(FILE_ACTION_URL)){
fileType = 0;
}else dsWith(IMAGE_ACTION_URL)){
fileType = 1;
}else dsWith(ICON_ACTION_URL)){
fileType = 2;
}
resp = FileUploaderUtil.upload((short)fileType,fileName, file, requestParams); //这⾥上传到s3
}
LOG.debug(resp);
return resp;
}
fileuploader.properties是s3服务的配置⽂件:
# s3,local,fastdfs
file_system=s3
public class FileUploaderUtil {
......
// Initialize S3 client configurations
static {
try {
properties = new Properties();
properties.load(ResourceAsStream(FILEUPLOADER_PROPERTIES));
URL url = Resource("/");//当前的classpath的绝对URI路径
uploadTemPath = new Path()).append(File.separator).append(UPLOAD_TEMP_DIR).toString();
//本地配置⽂件中的配置项
fileSystem = Property(FILE_SYSTEM).trim();
//zookeeper中如有对象配置项,以此为准
String zkFileSystem = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, FILE_SYSTEM);
if(StringUtils.isNotEmpty(zkFileSystem)){
fileSystem = zkFileSystem;
}
if (fileSystem.equalsIgnoreCase(FILE_SYSTEM_S3)) {
//本地配置⽂件中的配置项
awsAccessKey = Property(AWS_ACCESS_KEY).trim();
//zookeeper中如有对象配置项,以此为准
String zkAwsAccessKey = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, AWS_ACCESS_KEY);
if(StringUtils.isNotEmpty(zkAwsAccessKey)){
awsAccessKey = zkAwsAccessKey;
}
//本地配置⽂件中的配置项
awsSecretKey = Property(AWS_SECRET_KEY).trim();
//zookeeper中如有对象配置项,以此为准
String zkAwsSecretKey = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, AWS_SECRET_KEY);
if(StringUtils.isNotEmpty(zkAwsSecretKey)){
awsSecretKey = zkAwsSecretKey;
}
//本地配置⽂件中的配置项
bucketName = Property(BUCKET_NAME).trim();
//zookeeper中如有对象配置项,以此为准
String zkBucketName = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, BUCKET_NAME);
if(StringUtils.isNotEmpty(zkBucketName)){
bucketName = zkBucketName;
}
//本地配置⽂件中的配置项
endPoint = Property(END_POINT).trim();
//zookeeper中如有对象配置项,以此为准
String zkEndPoint = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, END_POINT);
if(StringUtils.isNotEmpty(zkEndPoint)){
endPoint = zkEndPoint;
}
BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
s3Client = new AmazonS3Client(awsCreds);
s3Client.setEndpoint(endPoint);
LOG.info("[FileManager]S3 connection established.");
}
//上传临时⽬录
File uploadTemp = new File(uploadTemPath);
// 创建⽬录
if (!ists()) {
uploadTemp.mkdirs();// ⽬录不存在的情况下,创建⽬录。
}
} catch (Exception ex) {
ex.printStackTrace();
<(ex.getMessage(), ex);
}
}
public static Boolean isS3(){
//zookeeper中如有对象配置项,以此为准
String zkFileSystem = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, FILE_SYSTEM);
if(StringUtils.isNotEmpty(zkFileSystem)){
fileSystem = zkFileSystem;
}
if (fileSystem.equalsIgnoreCase(FILE_SYSTEM_S3)) {
return true;
}else {
return false;
}
}
public static Boolean isLocal(){
//zookeeper中如有对象配置项,以此为准
String zkFileSystem = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, FILE_SYSTEM);
if(StringUtils.isNotEmpty(zkFileSystem)){
fileSystem = zkFileSystem;
}
if (fileSystem.equalsIgnoreCase(FILE_SYSTEM_LOCAL)) {
return true;
}else {
return false;
}
}
public static Boolean isFastDFS(){
//zookeeper中如有对象配置项,以此为准
String zkFileSystem = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, FILE_SYSTEM);
if(StringUtils.isNotEmpty(zkFileSystem)){
fileSystem = zkFileSystem;
}
if (fileSystem.equalsIgnoreCase(FILE_SYSTEM_FASTDFS)) {
return true;
}else {
return false;
}
}
public static String[] getS3GroupAndName(String fileUrl){
//本地配置⽂件中的配置项
endPoint = Property(END_POINT).trim();
//zookeeper中如有对象配置项,以此为准
String zkEndPoint = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, END_POINT);
if(StringUtils.isNotEmpty(zkEndPoint)){
endPoint = zkEndPoint;
}
String[] strArr = endPoint.split("");//end_point=s3-north-1.amazonaws
StringBuilder s3UrlSplit = new StringBuilder(".").append(strArr[1]).append("/"); //.s3-north-1.amazonaws/
//"rsbucket.s3-north-1.amazonaws/2015/05/29/60b9406e-8cf6-4bba-b0fc-xxxxxxxxxx.jpg"
//rsbucket,2015/05/29/60b9406e-8cf6-4bba-b0fc-xxxxxxxxxxx.jpg
String remoteName = StringUtils.substringAfter(fileUrl, String());
//设定group为bucketName,不从URL中截取
//处理file_system多次切换时,bucketName为Null,从zookeeper中获取配置
String remoteGroup = (bucketName!=null)?Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, String[] rlt = new String[]{remoteGroup,remoteName};
return rlt;
}
/**
* 上传⽂件
* IMAGE、ICON图⽚切割处理,适配原FileUploadServlet、ImageUploadServlet、IconUploadServlet
* @param fileName ⽂件名
* @param file 要上传的⽂件
* @param requestParams 请求参数
* @return上传后的返回响应
*/
public static String upload(short fileType, String fileName, File file, Map<String, String> requestParams) {
//每次上传时获取最新的bucketName
//zookeeper中如有对象配置项,以此为准
String zkBucketName = Instance().getSystemConfigValue(ZOOKEEPER_CONFIG_GROUP, BUCKET_NAME);
if(StringUtils.isNotEmpty(zkBucketName)){
bucketName = zkBucketName;
}
//从local切换为s3,未创建s3Client时
if (s3Client == null) {
//本地配置⽂件中的配置项
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论