文件上传到oss,废话不多说直接上代码!!!
package com.king.util;
import java.io.InputStream;
import java.util.Properties;
public class OssProperty {
private static OssProperty instance=null;
private String fileName="/oss.properties";
private Properties dbProps=null;
private OssProperty(){
InputStream is = getClass().getResourceAsStream(fileName);
if(dbProps==null){
dbProps = new Properties();
}
try {
dbProps.load(is);
}
catch (Exception e) {
System.err.println("不能读取属性文件. " +
"请确保db.properties在CLASSPATH指定的路径中");
return;
}
}
public static OssProperty getInstance(){
if(instance==null){
instance=new OssProperty();
}
return instance;
}
public String getProperty(String name,String defaultValue){
return dbProps.getProperty(name, defaultValue);
}
public String getPool(int number){
return dbProps.getProperty("Pool"+String.valueOf(number));
}
public Properties getDbProps() {
return dbProps;
}
public void setDbProps(Properties dbProps) {
this.dbProps = dbProps;
}
}
配置文件oss.properties
endpoint:oss-cn-hangzhou.aliyuncs.com
bucketName:321
ak:32131
sk:12321
package com.king.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ListBucketsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectAcl;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
public class OssDataPush {
private static String endpoint=OssProperty.getInstance().getProperty("endpoint", "");
private static String accessKeyId=OssProperty.getInstance().getProperty("ak", "");
private static String accessKeySecret=OssProperty.getInstance().getProperty("sk", "");
private static String bucketName=OssProperty.getInstance().getProperty("bucketName", "");
private static String key=OssProperty.getInstance().getProperty("key", "");
private static OssDataPush ossinstance=null;
private OSSClient ossClient=null;
public OSSClient getOssClient() {
return ossClient;
}
private OssDataPush(){
init();
}
public static OssDataPush getInstance(){
if (ossinstance==null)
ossinstance=new OssDataPush();
return ossinstance;
}
public void init(){
ClientConfiguration conf = new ClientConfiguration();
// 关闭CNAME选项。
conf.setSupportCname(false);
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret,conf);
System.out.println("Getting Started with OSS SDK for Java\n");
try {
/*
* Determine whether the bucket exists
*/
if (!ossClient.doesBucketExist(bucketName)) {
/*
* Create a new OSS bucket
*/
System.out.println("Creating bucket " + bucketName + "\n");
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
}catch(Exception e){
e.printStackTrace();
}
}
public void uploadFile(File f){
ossClient.putObject(new PutObjectRequest(bucketName, key, f));
boolean exists = ossClient.doesObjectExist(bucketName, key);
System.out.println("Does object " + bucketName + " exist? " + exists + "\n");
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.Default);
ObjectAcl objectAcl = ossClient.getObjectAcl(bucketName, key);
System.out.println("ACL:" + objectAcl.getPermission().toString());
}
public void uploadFile(InputStream ins,String key,String contentType){
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType(contentType);
ossClient.putObject(bucketName, key, ins,meta);
boolean exists = ossClient.doesObjectExist(bucketName, key);
System.out.println("Does object " + bucketName + " exist? " + exists + "\n");
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.Default);
ObjectAcl objectAcl = ossClient.getObjectAcl(bucketName, key);
System.out.println("ACL:" + objectAcl.getPermission().toString());
}
public InputStream downFile(String key){
InputStream in=null;
try {
OSSObject object = getOSSObject(key);//ossClient.getObject(bucketName, key);
System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
in=object.getObjectContent();
//displayTextInputStream(object.getObjectContent());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return in;
}
public OSSObject getOSSObject(String key){
OSSObject object=null;
try {
object = ossClient.getObject(bucketName, key);
System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
// in=object.getObjectContent();
//displayTextInputStream(object.getObjectContent());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
public String getFileUrl(String key){
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
return url.toString();
}
public static void main(String[] args) throws IOException {
/*
* Constructs a client instance with your account for accessing OSS
*/
//String fielurl=
// OssDataPush.getInstance().downFile("000ebc454206480781f0e5b022440a10");
// File f=new File("d:/test.png");
// OssDataPush.getInstance().uploadFile(f);
// getFileUrl("5b0decf308774cb0b3a46acf027c99e5");
//System.out.println(fielurl);
// if(true)
// return;
OSSClient ossClient = new OSSClient("", "", "");
ossClient.deleteObject("ddd", "000c5564559443f4bbcd3190f2e17681");
System.out.println("Getting Started with OSS SDK for Java\n");
if(true)return;
try {
/*
* Determine whether the bucket exists
*/
if (!ossClient.doesBucketExist(bucketName)) {
/*
* Create a new OSS bucket
*/
System.out.println("Creating bucket " + bucketName + "\n");
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
ossClient.deleteObject(bucketName, accessKeyId);
}
/*
* List the buckets in your account
*/
System.out.println("Listing buckets");
ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
listBucketsRequest.setMaxKeys(500);
for (Bucket bucket : ossClient.listBuckets()) {
System.out.println(" - " + bucket.getName());
}
System.out.println();
/*
* Upload an object to your bucket
*/
System.out.println("Uploading a new object to OSS from a file\n");
ossClient.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
/*
* Determine whether an object residents in your bucket
*/
boolean exists = ossClient.doesObjectExist(bucketName, key);
System.out.println("Does object " + bucketName + " exist? " + exists + "\n");
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.Default);
ObjectAcl objectAcl = ossClient.getObjectAcl(bucketName, key);
System.out.println("ACL:" + objectAcl.getPermission().toString());
/*
* Download an object from your bucket
*/
System.out.println("Downloading an object");
OSSObject object = ossClient.getObject(bucketName, key);
System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
displayTextInputStream(object.getObjectContent());
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
System.out.println("url==="+url);
/*
* List objects in your bucket by prefix
*/
System.out.println("Listing objects");
ObjectListing objectListing = ossClient.listObjects(bucketName, "My");
for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
System.out.println(" - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() + ")");
}
System.out.println();
/*
* Delete an object
*/
// System.out.println("Deleting an object\n");
// ossClient.deleteObject(bucketName, key);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message: " + oe.getErrorCode());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ce.getMessage());
} finally {
/*
* Do not forget to shut down the client finally to release all allocated resources.
*/
ossClient.shutdown();
}
}
private static File createSampleFile() throws IOException {
/* File file = File.createTempFile("oss-java-sdk-", ".txt");
file.deleteOnExit();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("0123456789011234567890\n");
writer.close();*/
File file=new File("h:/testimg.jpg");
return file;
}
private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println(" " + line);
}
System.out.println();
reader.close();
}
}
package com.king.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping({"/file"})
public class UploadFilesAction
{
RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate)
{
this.redisTemplate = redisTemplate; }
@RequestMapping(value={"/getfile/byid/{id}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
@ResponseBody
public String getFileUrl(@PathVariable("id") String id) throws Exception { String url = OssDataPush.getInstance().getFileUrl(id);
return url;
}
@RequestMapping(value={"/getfilestream/byid/{id}/{filename}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
@ResponseBody
public String getFileStream(@PathVariable("id") String id, @PathVariable("filename") String filename, HttpServletResponse response) throws Exception {
OSSObject object = OssDataPush.getInstance().getOSSObject(id);
InputStream in = object.getObjectContent();
OutputStream os =null;
try{
response.reset();
System.out.println("object===" + object);
String content = object.getObjectMetadata().getContentType();
response.setHeader("Content-disposition",
"inline; filename=" + filename);
response.addHeader("content-type", content);
in = object.getObjectContent();
os = response.getOutputStream();
byte[] buff = new byte[4096];
int len = -1;
while ((len = in.read(buff)) != -1)
os.write(buff, 0, len);
// os.flush();
// response.flushBuffer();
}catch(Exception e){
e.printStackTrace();
}finally{
if(in!=null){
in.close();
}
if(object!=null){
object.close();
}
if(os!=null){
os.close();
os.flush();
}
response.flushBuffer();
}
return null;
}
@RequestMapping(value={"/getfilestream/byid/{id}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
@ResponseBody
public String getFileStream(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
OSSObject object = OssDataPush.getInstance().getOSSObject(id);
InputStream in = object.getObjectContent();
OutputStream os =null;
try{
response.reset();
request.setCharacterEncoding("UTF-8");
String filename = request.getParameter("filename");
System.out.println("object===" + object);
filename = new String(filename.getBytes("ISO8859_1"), "utf-8");
System.out.println("filename===" + filename);
String content = object.getObjectMetadata().getContentType();
filename = new String(filename.getBytes("GBK"), "ISO8859_1");
response.setHeader("Content-disposition",
"inline; filename=" + filename);
response.addHeader("content-type", content);
os = response.getOutputStream();
byte[] buff = new byte[4096];
int len = -1;
while ((len = in.read(buff)) != -1)
os.write(buff, 0, len);
}catch(Exception e){
e.printStackTrace();
}finally{
if(in!=null){
in.close();
}
if(object!=null){
object.close();
}
if(os!=null){
os.close();
os.flush();
}
response.flushBuffer();
}
return null;
}
@RequestMapping(value={"/getfilestreamDownLoad/byid/{id}/{filename}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
@ResponseBody
public void getfilestreamDownLoad(@PathVariable("id") String id, @PathVariable("filename") String filename, HttpServletResponse response)
throws Exception
{
OSSObject object = OssDataPush.getInstance().getOSSObject(id);
System.out.println("object===" + object);
String content = object.getObjectMetadata().getContentType();
InputStream in = object.getObjectContent();
OutputStream os = response.getOutputStream();
byte[] buff = new byte[4096];
int len = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = in.read(buff)) != -1)
baos.write(buff, 0, len);
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
os.write(baos.toByteArray());
os.close();
}
@RequestMapping(value={"/getfilestreamDownLoad/byid/{id}"}, method={org.springframework.web.bind.annotation.RequestMethod.GET})
@ResponseBody
public void getfilestreamDownLoad(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws Exception
{
OSSObject object = OssDataPush.getInstance().getOSSObject(id);
request.setCharacterEncoding("UTF-8");
String filename = request.getParameter("filename");
filename = new String(filename.getBytes("ISO8859_1"), "utf-8");
System.out.println("filename===" + filename);
String content = object.getObjectMetadata().getContentType();
filename = new String(filename.getBytes("GBK"), "ISO8859_1");
InputStream in = object.getObjectContent();
OutputStream os = response.getOutputStream();
byte[] buff = new byte[4096];
int len = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = in.read(buff)) != -1)
baos.write(buff, 0, len);
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
os.write(baos.toByteArray());
os.close();
}
@RequestMapping({"uploadfile/upload"})
public String upLoadFiles(@RequestParam MultipartFile[] file, HttpServletRequest request, HttpServletResponse response)
throws IOException
{
MultipartFile[] arrayOfMultipartFile;
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT");
response.setHeader("P3P", "CP='CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR'");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject jsonlist = new JSONObject();
JSONArray jarry = new JSONArray();
int j = (arrayOfMultipartFile = file).length; for (int i = 0; i < j; ++i) { MultipartFile myfile = arrayOfMultipartFile[i];
if (myfile.isEmpty()) {
System.out.println("文件未上传");
out.println("文件未上传");
return null;
}
System.out.println("文件长度: " + myfile.getSize());
System.out.println("文件类型: " + myfile.getContentType());
System.out.println("文件名称: " + myfile.getName());
System.out.println("文件原名: " + myfile.getOriginalFilename());
String uuid = UUID.randomUUID().toString().replace("-", "");
JSONObject jsonobj = new JSONObject();
jsonobj.put("size", Long.valueOf(myfile.getSize() / 1024L));
jsonobj.put("type", myfile.getContentType());
jsonobj.put("name", myfile.getOriginalFilename());
jsonobj.put("uuid", uuid);
System.out.println("jsonobj==" + jsonobj.toString());
try
{
InputStream is = myfile.getInputStream();
OssDataPush.getInstance().uploadFile(is, uuid, myfile.getContentType());
jarry.add(jsonobj);
is.close();
}
catch (Exception e)
{
e.printStackTrace();
out.print("文件上传失败,请重试!!");
}
}
jsonlist.put("filelist", jarry);
System.out.println("jsonlist==" + jsonlist.toString());
String calllurl = request.getParameter("calllurl");
System.out.println("calllurl==" + calllurl + "calllurl");
if ((calllurl == null) || ("false".equals(calllurl.trim())))
{
System.out.println("into jsonlist==" + jsonlist.toString());
out.println(jsonlist.toString());
out.flush();
return null;
}
System.out.println("redirect:http://" + calllurl + "?data=" + URLEncoder.encode(jsonlist.toString()));
return "redirect:http://" + calllurl + "?data=" + URLEncoder.encode(jsonlist.toString());
}
public String getFileListJson()
{
String ret = "";
return ret;
}
public static void main(String[] args) {
OSSClient ossClient = new OSSClient("", "", "");
ossClient.deleteObject("", "");
}
}