Java上传华为云OBS图片

import com.obs.services.ObsClient;
import com.obs.services.model.ObjectMetadata;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class ObsUploadUtil {
	//OBS图片访问域名
	public static String endPoint = "*******";
	public static String accessKeyId = "*******";
	public static String accessKeySecret = "*******";
	public static String bucketName = "*******";
	public static String oss_domain = "*******";


	// 创建ObsClient实例
	public static ObsClient obsClient = new ObsClient(accessKeyId, accessKeySecret, endPoint);

	public static String obsUpload(HttpServletRequest request,  MultipartFile file) throws IOException{
		//CommonsMultipartFile file = (CommonsMultipartFile)multipartFile;
		String fileName = "";
		if(file!=null && !"".equals(file.getOriginalFilename()) && file.getOriginalFilename()!=null){
			InputStream content = file.getInputStream();//获得指定文件的输入流
			ObjectMetadata meta = new ObjectMetadata();// 创建上传Object的Metadata
			meta.setContentLength(file.getSize());  // 必须设置ContentLength
			String originalFilename = file.getOriginalFilename();
			fileName =  UUID.randomUUID().toString().replaceAll("-","") + originalFilename.subSequence(originalFilename.lastIndexOf("."), originalFilename.length());
			obsClient.putObject(bucketName,"admin/"+fileName,content,meta);// 上传Object.
			if(fileName != null && !"".equals(fileName)){
				System.out.println(fileName);
				fileName = oss_domain+"admin/"+fileName;
			}
		}
		return fileName;
	}

	/**
	 * 删除某个Object
	 *
	 * @param bucketUrl
	 * @return
	 */
	public static boolean deleteObject(String bucketUrl) {
		try {
			bucketUrl=bucketUrl.replace(oss_domain+"web","");
			// 删除Object.
			obsClient.deleteObject(bucketName, bucketUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			//ossClient.shutdown();
		}
		return true;
	}
}

你可能感兴趣的:(Java)