之前项目中用到了阿里云OSS存储图片,但是在ueditor富文本编辑器中的自带上传图片方法却是上传到本地的,改的时候绞尽脑汁,改完之后却又发现简单至极~
图片中画红框的地方是我改过的文件,只有这两个文件进行了修改,再添加一个阿里云的上传方法类就没了
下面这个是我的Uploader.java文件里的内容,我在网上看到有别人的这个文件里的方法和我的不太一样,这里贴出来我的类,我只改了里面upload方法的上传部分。
package com.fh.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import com.fh.util.aliyun.AliyunOSSClientUtil;
import Decoder.BASE64Decoder;
/**
* UEditor(百度编辑器)文件上传辅助类
*
*/
public class Uploader {
// 文件大小常量, 单位kb
private static final int MAX_SIZE = 500 * 1024;
// 输出文件地址
private String url = "";
// 上传文件名
private String fileName = "";
// 状态
private String state = "";
// 文件类型
private String type = "";
// 原始文件名
private String originalName = "";
// 文件大小
private String size = "";
private HttpServletRequest request = null;
private String title = "";
// 保存路径
private String savePath = "upload";
// 文件允许格式
private String[] allowFiles = {".rar", ".doc", ".docx", ".zip", ".pdf",
".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp"};
// 文件大小限制,单位Byte
private long maxSize = 0;
private HashMap<String, String> errorInfo = new HashMap<String, String>();
private Map<String, String> params = null;
// 上传的文件数据
private InputStream inputStream = null;
public static final String ENCODEING = System.getProperties()
.getProperty("file.encoding");
public Uploader(HttpServletRequest request) {
this.request = request;
this.params = new HashMap<String, String>();
this.setMaxSize(Uploader.MAX_SIZE);
HashMap<String, String> tmp = this.errorInfo;
tmp.put("SUCCESS", "SUCCESS"); // 默认成功
// 未包含文件上传域
tmp.put("NOFILE",
"\\u672a\\u5305\\u542b\\u6587\\u4ef6\\u4e0a\\u4f20\\u57df");
// 不允许的文件格式
tmp.put("TYPE",
"\\u4e0d\\u5141\\u8bb8\\u7684\\u6587\\u4ef6\\u683c\\u5f0f");
// 文件大小超出限制
tmp.put("SIZE",
"\\u6587\\u4ef6\\u5927\\u5c0f\\u8d85\\u51fa\\u9650\\u5236");
// 请求类型错误
tmp.put("ENTYPE", "\\u8bf7\\u6c42\\u7c7b\\u578b\\u9519\\u8bef");
// 上传请求异常
tmp.put("REQUEST", "\\u4e0a\\u4f20\\u8bf7\\u6c42\\u5f02\\u5e38");
// 未找到上传文件
tmp.put("FILE", "\\u672a\\u627e\\u5230\\u4e0a\\u4f20\\u6587\\u4ef6");
// IO异常
tmp.put("IO", "IO\\u5f02\\u5e38");
// 目录创建失败
tmp.put("DIR", "\\u76ee\\u5f55\\u521b\\u5efa\\u5931\\u8d25");
// 未知错误
tmp.put("UNKNOWN", "\\u672a\\u77e5\\u9519\\u8bef");
this.parseParams();
}
public void upload() throws Exception {
boolean isMultipart = ServletFileUpload
.isMultipartContent(this.request);
if (!isMultipart) {
this.state = this.errorInfo.get("NOFILE");
return;
}
if (this.inputStream == null) {
this.state = this.errorInfo.get("FILE");
return;
}
// 存储title
this.title = this.getParameter("pictitle");
try {
String savePath = this.getFolder(this.savePath);
if (!this.checkFileType(this.originalName)) {
this.state = this.errorInfo.get("TYPE");
return;
}
this.fileName = this.getName(this.originalName);
this.type = this.getFileExt(this.fileName);
this.url = savePath + "/" + this.fileName;
// 上传图片
AliyunOSSClientUtil.uploadImgAliyun(this.inputStream,savePath + "/"+ this.fileName,"gainianpublicimg");
// 原本的上传方法
// FileOutputStream fos = new FileOutputStream(
// this.getPhysicalPath(this.url));
// BufferedInputStream bis = new BufferedInputStream(this.inputStream);
// byte[] buff = new byte[128];
// int count = -1;
//
// while ((count = bis.read(buff)) != -1) {
//
// fos.write(buff, 0, count);
//
// }
//
// bis.close();
// fos.close();
this.state = this.errorInfo.get("SUCCESS");
} catch (Exception e) {
e.printStackTrace();
this.state = this.errorInfo.get("IO");
}
}
/**
* 接受并保存以base64格式上传的文件
*
* @param fieldName
*/
public void uploadBase64(String fieldName) {
String savePath = this.getFolder(this.savePath);
String base64Data = this.request.getParameter(fieldName);
this.fileName = this.getName("test.png");
this.url = savePath + "/" + this.fileName;
BASE64Decoder decoder = new BASE64Decoder();
try {
File outFile = new File(this.getPhysicalPath(this.url));
OutputStream ro = new FileOutputStream(outFile);
byte[] b = decoder.decodeBuffer(base64Data);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
ro.write(b);
ro.flush();
ro.close();
this.state = this.errorInfo.get("SUCCESS");
} catch (Exception e) {
this.state = this.errorInfo.get("IO");
}
}
public String getParameter(String name) {
return this.params.get(name);
}
/**
* 文件类型判断
*
* @param fileName
* @return
*/
private boolean checkFileType(String fileName) {
Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
/**
* 获取文件扩展名
*
* @return string
*/
private String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
private void parseParams() {
DiskFileItemFactory dff = new DiskFileItemFactory();
try {
ServletFileUpload sfu = new ServletFileUpload(dff);
sfu.setSizeMax(this.maxSize);
sfu.setHeaderEncoding(Uploader.ENCODEING);
FileItemIterator fii = sfu.getItemIterator(this.request);
while (fii.hasNext()) {
FileItemStream item = fii.next();
// 普通参数存储
if (item.isFormField()) {
this.params.put(item.getFieldName(),
this.getParameterValue(item.openStream()));
} else {
// 只保留一个
if (this.inputStream == null) {
this.inputStream = item.openStream();
this.originalName = item.getName();
return;
}
}
}
} catch (Exception e) {
this.state = this.errorInfo.get("UNKNOWN");
}
}
/**
* 依据原始文件名生成新文件名
*
* @return
*/
private String getName(String fileName) {
Random random = new Random();
return this.fileName = "" + random.nextInt(10000)
+ System.currentTimeMillis() + this.getFileExt(fileName);
}
/**
* 根据字符串创建本地目录 并按照日期建立子目录返回
*
* @param path
* @return
*/
private String getFolder(String path) {
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
path += "/" + formater.format(new Date());
File dir = new File(this.getPhysicalPath(path));
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
this.state = this.errorInfo.get("DIR");
return "";
}
}
return path;
}
/**
* 根据传入的虚拟路径获取物理路径
*
* @param path
* @return
*/
private String getPhysicalPath(String path) {
String servletPath = this.request.getServletPath();
String realPath = this.request.getSession().getServletContext()
.getRealPath(servletPath);
return new File(realPath).getParent() + "/" + path;
}
/**
* 从输入流中获取字符串数据
*
* @param in
* 给定的输入流, 结果字符串将从该流中读取
* @return 从流中读取到的字符串
*/
private String getParameterValue(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result = "";
String tmpString = null;
try {
while ((tmpString = reader.readLine()) != null) {
result += tmpString;
}
} catch (Exception e) {
// do nothing
}
return result;
}
private byte[] getFileOutputStream(InputStream in) {
try {
return IOUtils.toByteArray(in);
} catch (IOException e) {
return null;
}
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public void setAllowFiles(String[] allowFiles) {
this.allowFiles = allowFiles;
}
public void setMaxSize(long size) {
this.maxSize = size * 1024;
}
public String getSize() {
return this.size;
}
public String getUrl() {
return this.url;
}
public String getFileName() {
return this.fileName;
}
public String getState() {
return this.state;
}
public String getTitle() {
return this.title;
}
public String getType() {
return this.type;
}
public String getOriginalName() {
return this.originalName;
}
}
ueditor.config.js文件里的只是把imagePath改成了OSS读取图片的前缀
除了这两处别的都没有改动,另有阿里云的上传方法类一个在下面粘出来
package com.fh.util.aliyun;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import org.apache.log4j.Logger;
import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
/**
* @class:AliyunOSSClientUtil
* @descript:java使用阿里云OSS存储对象上传图片
* @date:2017年3月16日 下午5:58:08
* @author sang
*/
public class AliyunOSSClientUtil {
//log日志
private static Logger logger = Logger.getLogger(AliyunOSSClientUtil.class);
//阿里云API的内或外网域名
private static String ENDPOINT;
//阿里云API的密钥Access Key ID
private static String ACCESS_KEY_ID;
//阿里云API的密钥Access Key Secret
private static String ACCESS_KEY_SECRET;
//阿里云API的bucket名称
private static String BACKET_NAME;
//阿里云API的文件夹名称
private static String FOLDER;
//private static OSSClient ossClient;
//初始化属性
static{
ENDPOINT = allocation.ENDPOINT;
ACCESS_KEY_ID = allocation.ACCESS_KEY_ID;
ACCESS_KEY_SECRET = allocation.ACCESS_KEY_SECRET;
BACKET_NAME = allocation.BACKET_NAME;
FOLDER = allocation.FOLDER;
}
/**
* 获取阿里云OSS客户端对象
* @return ossClient
*/
public static OSSClient test(){
System.out.println("test");
return null;
}
/**
* 创建存储空间
* @param ossClient OSS连接
* @param bucketName 存储空间
* @return
*/
public static String createBucketName(OSSClient ossClient,String bucketName){
//存储空间
final String bucketNames=bucketName;
if(!ossClient.doesBucketExist(bucketName)){
//创建存储空间
Bucket bucket=ossClient.createBucket(bucketName);
logger.info("创建存储空间成功");
return bucket.getName();
}
return bucketNames;
}
/**
* 删除存储空间buckName
* @param ossClient oss对象
* @param bucketName 存储空间
*/
public static void deleteBucket(OSSClient ossClient, String bucketName){
ossClient.deleteBucket(bucketName);
logger.info("删除" + bucketName + "Bucket成功");
}
/**
* 创建模拟文件夹
* @param ossClient oss连接
* @param bucketName 存储空间
* @param folder 模拟文件夹名如"qj_nanjing/"
* @return 文件夹名
*/
public static String createFolder(OSSClient ossClient,String bucketName,String folder){
//文件夹名
final String keySuffixWithSlash =folder;
//判断文件夹是否存在,不存在则创建
if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){
//创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
logger.info("创建文件夹成功");
//得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir=object.getKey();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 根据key删除OSS服务器上的文件
* @param ossClient oss连接
* @param bucketName 存储空间
* @param folder 模拟文件夹名 如"qj_nanjing/"
* @param key Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
*/
public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key){
ossClient.deleteObject(BACKET_NAME, FOLDER + key);
logger.info("删除" + BACKET_NAME + "下的文件" + FOLDER + key + "成功");
}
public static void uploadImgAliyun(InputStream inputStream ,String fileName, String bucketName)
throws FileNotFoundException{
OSSClient client = new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
//此处"images/companyNewsImages/"+fileName,表示上传至阿里云中images文件夹下的companyNewsImages文件夹中,请修改为自己的路径即可
client.putObject(bucketName, fileName, inputStream);
client.shutdown();
}
/**
* 上传图片至OSS
* @param ossClient oss连接
* @param file 上传文件(文件全路径如:D:\\image\\cake.jpg)
* @param bucketName 存储空间
* @param folder 模拟文件夹名 如"qj_nanjing/"
* @return String 返回的唯一MD5数字签名
* */
public static String uploadObject2OSS(OSSClient ossClient, File file, String bucketName, String folder) {
String resultStr = null;
try {
//以输入流的形式上传文件
InputStream is = new FileInputStream(file);
//文件名
String fileName = file.getName();
System.out.println(fileName);
//文件大小
Long fileSize = file.length();
//创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
//上传的文件的长度
metadata.setContentLength(is.available());
//指定该Object被下载时的网页的缓存行为
metadata.setCacheControl("no-cache");
//指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
//指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
//文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
//如果没有扩展名则填默认值application/octet-stream
metadata.setContentType(getContentType(fileName));
//指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
//上传文件 (上传文件流的形式)
PutObjectResult putResult =
ossClient.putObject(bucketName, folder + fileName, is, metadata);
//解析结果
resultStr = folder+fileName;
System.out.println(putResult.getETag());
System.out.println(resultStr);
} catch (Exception e) {
e.printStackTrace();
logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
}
return resultStr;
}
/**
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
* @param fileName 文件名
* @return 文件的contentType
*/
public static String getContentType(String fileName){
//文件的后缀名
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
if(".bmp".equalsIgnoreCase(fileExtension)) {
return "image/bmp";
}
if(".gif".equalsIgnoreCase(fileExtension)) {
return "image/gif";
}
if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension) ) {
return "image/jpeg";
}
if(".html".equalsIgnoreCase(fileExtension)) {
return "text/html";
}
if(".txt".equalsIgnoreCase(fileExtension)) {
return "text/plain";
}
if(".vsd".equalsIgnoreCase(fileExtension)) {
return "application/vnd.visio";
}
if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
return "application/vnd.ms-powerpoint";
}
if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
return "application/msword";
}
if(".xml".equalsIgnoreCase(fileExtension)) {
return "text/xml";
}
//默认返回类型
return "image/jpeg";
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public static String getImgUrl(String fileUrl,OSSClient ossClient,String bucketName) {
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return getUrl(FOLDER + split[split.length - 1],ossClient,bucketName);
}
return null;
}
/**
* 获得url链接
*
* @param key
* @return
*/
public static String getUrl(String key,OSSClient ossClient,String bucketName) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
}
之前用的uploadObject2OSS方法上传只能上传上去一点点,大概有2kb多点,上传不完整,猜测大概是metadata参数传的不对吧,具体原因仍旧不太明白,如有大神知道可以在留言处告知,不胜感激。