package com.yq1012.oss; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import com.aliyun.oss.OSSClient; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; /** * Created by Administrator on 2016/2/17. */ public class UploadOss { public static boolean putObject() throws FileNotFoundException { // key指的是 保存在oss上后的路径+文件名 // filePath 指的是上传的文件路径 OSSClient client; //参数设置 //关于这个endPoint,可以参考:http://bbs.aliyun.com/read/149100.html?spm=5176.7189909.0.0.YiwiFw String endpoint = "http://oss-cn-qingdao.aliyuncs.com/";//青岛的接口 String accessKeyId = "javaweb.top"; String accessKeySecret = "javaweb.top"; String bucketName = "yq1012"; String key="ceshi.jpg";//保存在oss上的文件名 String filePath="d://7.jpg";//本地或者服务器上文件的路径 boolean flag=false; try{ client = new OSSClient(endpoint,accessKeyId, accessKeySecret); // 获取指定文件的输入流 File file = new File(filePath); InputStream content = new FileInputStream(file); // 创建上传Object的Metadata ObjectMetadata meta = new ObjectMetadata(); // 必须设置ContentLength meta.setContentLength(file.length()); // 上传Object. PutObjectResult result = client.putObject(bucketName, key, content, meta); if (file.isFile() && file.exists()) { // file.delete(); flag = true; } }catch(OSSException oe){ 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()); flag=false; }finally { return flag; } // 打印ETag // System.out.println(result.getETag()); } public static void main(String[] args) { try { System.out.println(putObject()); } catch (FileNotFoundException e) { e.printStackTrace(); } } }