Java上傳圖片到OSS

上傳主方法


package cn.osworks.aos.huijia.modules.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;


public class UploadFile {
/**
* 阿里雲ACCESS_ID
*/
// ID:aQFi66LcWwC8TbWP
// KEY:UIahtOgRNT4nPpykOorrDsl3K22Pas


private static String ACCESS_ID = "LTAIxXgQ6Zj1pwb7";
/**
* 阿里雲ACCESS_KEY
*/
private static String ACCESS_KEY = "3bV63KYqCBpoXjiFIjAImIW3Venv7l";
/**
* 阿里雲OSS_ENDPOINT 青島Url
*/
private static String OSS_ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";


/**
* 阿里雲BUCKET_NAME OSS
*/
private static String BUCKET_NAME = "huijw";

public static String BTY(String Objectkey,String uploadFilePath){
OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
try {
ensureBucket(client, BUCKET_NAME);
setBucketPublicReadable(client, BUCKET_NAME);


System.out.println("正在上傳...");
uploadFile(client, BUCKET_NAME, Objectkey, uploadFilePath);

// client.deleteObject(BUCKET_NAME, Objectkey);
// deleteBucket(client, Objectkey);
// System.out.println("正在下載...");
// downloadFile(client, BUCKET_NAME, Objectkey, downloadFilePath);
} catch (Exception e) {
e.printStackTrace();
} finally {

}
return Objectkey;
}



public static void main(String[] args) {
// String bucketName = "demo10";
String Objectkey = "head/banner-4.png";


String uploadFilePath = "D:/banner-4.png";
// String downloadFilePath = "/Users/liaomc/Desktop/hs2.jpg";


// 如果你想配置OSSClient的一些細節的參數,可以在構造OSSClient的時候傳入ClientConfiguration對象。
// ClientConfiguration是OSS服務的配置類,可以爲客戶端配置代理,最大連接數等參數。
// 具體配置看http://aliyun_portal_storage.oss.aliyuncs.com/oss_api/oss_javahtml/OSSClient.html#id2
// ClientConfiguration conf = new ClientConfiguration();
// OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY,
// conf);
// 創建ClientConfiguration實例


// 使用默認的OSS服務器地址創建OSSClient對象,不叫OSS_ENDPOINT代表使用杭州節點,青島節點要加上不然包異常
OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
try {
ensureBucket(client, BUCKET_NAME);
setBucketPublicReadable(client, BUCKET_NAME);


System.out.println("正在上傳...");
uploadFile(client, BUCKET_NAME, Objectkey, uploadFilePath);


// client.deleteObject(BUCKET_NAME, Objectkey);
// deleteBucket(client, Objectkey);
// System.out.println("正在下載...");
// downloadFile(client, BUCKET_NAME, Objectkey, downloadFilePath);
} catch (Exception e) {
e.printStackTrace();
} finally {

}
}
/**
* 上傳文件

* @param client
*            OSSClient對象
* @param bucketName
*            Bucket名
* @param Objectkey
*            上傳到OSS起的名
* @param filename
*            本地文件名
* @throws OSSException
* @throws ClientException
* @throws FileNotFoundException
*/
private static void uploadFile(OSSClient client, String bucketName,
String Objectkey, String filename) throws OSSException,
ClientException, FileNotFoundException {
File file = new File(filename);
ObjectMetadata objectMeta = new ObjectMetadata();
//String md5 = objectMeta.getContentMD5();
//System.out.println(md5);
objectMeta.setContentLength(file.length());
// 判斷上傳類型,多的可根據自己需求來判定
if (filename.endsWith("xml")) {
objectMeta.setContentType("text/xml");
} else if (filename.endsWith("jpg")) {
objectMeta.setContentType("image/jpeg");
} else if (filename.endsWith("png")) {
objectMeta.setContentType("image/png");
}


InputStream input = new FileInputStream(file);
PutObjectResult result = client.putObject(bucketName, Objectkey, input,
objectMeta);
// 打印ETag
System.out.println(result.getETag());
//if (md5.equals(result.getETag()))
System.out.println("上傳完成");
}


/**
* 創建Bucket

* @param client
*            OSSClient對象
* @param bucketName
*            BUCKET名
* @throws OSSException
* @throws ClientException
*/
public static void ensureBucket(OSSClient client, String bucketName)
throws OSSException, ClientException {
try {
client.createBucket(bucketName);
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
} catch (ServiceException e) {
if (!OSSErrorCode.BUCKET_ALREADY_EXISTS.equals(e.getErrorCode())) {
throw e;
}
}
}


/**
* 刪除一個Bucket和其中的Objects

* @param client
*            OSSClient對象
* @param bucketName
*            Bucket名
* @throws OSSException
* @throws ClientException
*/
private static void deleteBucket(OSSClient client, String bucketName)
throws OSSException, ClientException {
ObjectListing ObjectListing = client.listObjects(bucketName);
List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
for (int i = 0; i < listDeletes.size(); i++) {
String objectName = listDeletes.get(i).getKey();
System.out.println("objectName = " + objectName);
// 如果不爲空,先刪除bucket下的文件
client.deleteObject(bucketName, objectName);
}
client.deleteBucket(bucketName);
}


/**
* 把Bucket設置成所有人可讀

* @param client
*            OSSClient對象
* @param bucketName
*            Bucket名
* @throws OSSException
* @throws ClientException
*/
private static void setBucketPublicReadable(OSSClient client,
String bucketName) throws OSSException, ClientException {
// 創建bucket
client.createBucket(bucketName);


// 設置bucket的訪問權限, public-read-write權限
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}




/**
* 下載文件

* @param client
*            OSSClient對象
* @param bucketName
*            Bucket名
* @param Objectkey
*            上傳到OSS起的名
* @param filename
*            文件下載到本地保存的路徑
* @throws OSSException
* @throws ClientException
*/
private static void downloadFile(OSSClient client, String bucketName,
String Objectkey, String filename) throws OSSException,
ClientException {
client.getObject(new GetObjectRequest(bucketName, Objectkey), new File(
filename));
}

}

前端調用


---------------引入libjar包
《-----------------前端-------------》


<aos:window id="_w_deploy" title="上傳圖片">
<aos:formpanel id="_f_deploy" width="450" layout="column" labelWidth="70">
<aos:filefield name="pic_file" fieldLabel="圖片" buttonText="選擇圖片" allowBlank="false" columnWidth="0.99"
emptyText="請選擇圖片文件..." />
</aos:formpanel>
<aos:docked dock="bottom" ui="footer">
<aos:dockeditem xtype="tbfill" />
<aos:dockeditem οnclick="_f_deploy_save" text="上傳" icon="ok.png" />
<aos:dockeditem οnclick="#_w_deploy.hide();" text="關閉" icon="close.png" />
</aos:docked>
</aos:window>




//部署(注:文件上傳操作不能使用AOS.Ajax()方法,只能使用Form自帶的submit()函數)。
  function _f_deploy_save() {
      var form = _f_deploy.getForm();
      if (!form.isValid()) {
  return;
      }
      AOS.wait();
      form.submit({
  url: 'uploadPic.jhtml',
  success: function (form, action) {
      //_w_deploy.hide();
      AOS.
      AOS.hide();
     // AOS.tip();
      AOS.tip("上傳完成");
      _g_proc_query();
  }
      });
  }




《-----------------上傳圖片action-------------》
/**
* 上傳圖片
* @param session
* @param request
* @return
* @throws IOException 
*/
@RequestMapping(value = "uploadPic")
public void uploadPic(
@RequestParam("pic_file") MultipartFile pic_file ,
HttpServletRequest request,HttpServletResponse response) throws IOException {


/*HttpServletRequest request= httpModel.getRequest();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
MultipartFile myFile = multipartRequest.getFile("myFile"); */
Dto inDto = Dtos.newDto(request);
inDto.put("pic_file", pic_file);

Dto outDto = tbadvertservice.uploadPic(inDto,request);
WebCxt.write(response, AOSJson.toJson(outDto));
}
《-----------------上傳圖片service-------------》
/**
* 上傳圖片
* @param inDto
* @param request2 
* @return
* @throws IOException 
*/
public Dto uploadPic(Dto inDto, HttpServletRequest request) throws IOException {

Dto outDto = Dtos.newOutDto();


MultipartFile picFile= (MultipartFile) inDto.get("pic_file");
//判斷圖片格式
if (StringUtils.indexOf(picFile.getOriginalFilename(), ".jpg") == -1) {
outDto.setAppMsg("操作被取消,只能上傳.jpg格式的圖片。");
return outDto;
}
//圖片存儲到本地服務器
String path=request.getSession().getServletContext().getRealPath("/upload/");
//取後綴
   String suffix = picFile.getOriginalFilename().substring(picFile.getOriginalFilename().lastIndexOf("."));
   //存儲到本地的圖片名稱
   String fileName =picFile.getOriginalFilename(); 
   
   //本地目的地址
   String destDir=path+"/"+fileName;
   File f=new File(path,fileName);
   picFile.transferTo(f);
            //"advert"+"/"   服務器路徑
   String upImageToOSS = upImageToOSS("advert"+"/"+fileName, destDir);
System.out.println(upImageToOSS);


outDto.setAppMsg("上傳圖片成功。");

outDto.setStringA(upImageToOSS);
return outDto;
}


-------- 在需要調用的service裏面定義如下方法
/**
* 圖片上傳本OSS
Objectkey:服務器路徑
uploadFilePath:本地路徑
*/
public String  upImageToOSS(String Objectkey,String uploadFilePath) {
/*String Objectkey = "head/f.jpg";


String uploadFilePath = "D:/w.jpg";*/
String bty = UploadFile.BTY(Objectkey, uploadFilePath);
return bty;
}


------------------調用UploadFile.java

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章