首页 > 编程 > Java > 正文

java上传图片到阿里云

2019-11-08 01:17:59
字体:
来源:转载
供稿:网友
//接收前端传来base64   并转化  存在本地public class Base64Image{ //PRivate static HttpServletRequest request = ServletActionContext.getRequest();public static void main(String[] args) {    // 测试从Base64编码转换为图片文件    String strImg = "base64编码";    GenerateImage(strImg, "D:/k.jpg");    System.out.println("aaa");    // 测试从图片文件转换为Base64编码   // System.out.println(GetImageStr("d://wangyc.jpg"));  }// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理  public static String GetImageStr(String imgFilePath) {    byte[] data = null;         // 读取图片字节数组    try {      InputStream in = new FileInputStream(imgFilePath);      data = new byte[in.available()];      in.read(data);      in.close();    } catch (IOException e) {      e.printStackTrace();    }         // 对字节数组Base64编码    BASE64Encoder encoder = new BASE64Encoder();    return encoder.encode(data);// 返回Base64编码过的字节数组字符串  }   public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片    if (imgStr == null) // 图像数据为空      return false;    BASE64Decoder decoder = new BASE64Decoder();    try {      // Base64解码      byte[] bytes = decoder.decodeBuffer(imgStr);      for (int i = 0; i < bytes.length; ++i) {        if (bytes[i] < 0) {// 调整异常数据          bytes[i] += 256;        }      }      // 生成jpeg图片      OutputStream out = new FileOutputStream(imgFilePath);      out.write(bytes);      out.flush();      out.close();      return true;    } catch (Exception e) {      return false;    }  }public static String getPrimaryKey(){ SimpleDateFormat simpleDateFormat;  simpleDateFormat = new SimpleDateFormat("hhMMss");  Date date = new Date();  String str = simpleDateFormat.format(date);  Random random = new Random();  int rannum = (int) (random.nextDouble() * (999 - 100 + 1)) + 10;// 获取2位随机数  System.out.println(str+rannum);// 当前时间 return str+rannum;  //return str;}}//上传图片到OSSpackage com.huijia.erp.uploadpic;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:UIahtOgRNT4nPpykOorrDsl3K22Pasprivate static String ACCESS_ID = "LTAIGNvEeBVhnCiU";/** * 阿里云ACCESS_KEY */private static String ACCESS_KEY = "CvPsE6RgP0mvMGUkpcHKWLyaiSD5JZ";/** * 阿里云OSS_ENDPOINT 青岛Url */private static String OSS_ENDPOINT = "http://oss-cn-shanghai.aliyuncs.com";/** * 阿里云BUCKET_NAME OSS */private static String BUCKET_NAME = "hjwang";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/n.jpg";String uploadFilePath = "D:/n.jpg";// 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);// 打印ETagSystem.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 {// 创建bucketclient.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));}}//调用的actionstrut2上传文件actionpackage com.huijia.erp.uploadpic;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.huijia.erp.entity.Result;import com.opensymphony.xwork2.ActionSupport;public class Uploadp {    private String base64;    public String getBase64() {        return base64;    }    public void setBase64(String base64) {        this.base64 = base64;    }    private String ossPath;        public String getOssPath() {return ossPath;}public void setOssPath(String ossPath) {this.ossPath = ossPath;}public void up(){     try {          HttpServletRequest request = ServletActionContext.getRequest();              //upload是图片上传路径              String dir = request.getRealPath("/upload");              String contextPath = request.getContextPath();              System.out.println(dir);     //System.out.println(base64.replace(" ", "+").substring(base64.indexOf(",")+1));`     //将图片截取     //String imageStr=base64.replace(" ", "+").substring(base64.indexOf(",")+1);                     String imageStr="base64";     //System.out.println(base64.replace(" ", "").length());    //图片名称     String picName=getPrimaryKey()+".jpg";    //本地目的地址     String destDir=dir+"/"+picName;     //上传图片到本地服务器下的upload文件夹下     Base64Image.GenerateImage(imageStr,destDir );     //上传到OSS     String upImageToOSS = upImageToOSS("body"+"/"+picName, destDir);            //String fileUrl = UploadTool.upload(base64.replace(" ", "+"));           // System.out.println("上传文件路径是:upload/" + fileUrl);     write(upImageToOSS);        } catch(Exception e) {            System.out.println(e);        }    }    /** * 图片上传本OSS */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;}    public Result uploadFile(String ext, ByteBuffer writebuf, int wrilen){Result result = new Result();if (writebuf.array().length != wrilen) {result.status = -1;result.message = "length error";return result;}//图片路径String pathname = "/upload";Random random = new Random();String rd = String.format("%04d",new Object[] { Integer.valueOf(random.nextInt(10000)) });String filename = System.currentTimeMillis() + rd + "." + ext;pathname = pathname + filename;result.status = ((short) writeFileStream(pathname, writebuf,wrilen));if (result.status == 0)result.message = filename;else {result.message = "上传文件失败";}return result;}public static int writeFileStream(String filename, ByteBuffer writebuf,int count) {int ret = -1;try {FileOutputStream outSTr = new FileOutputStream(new File(filename));BufferedOutputStream Buff = new BufferedOutputStream(outSTr);byte[] bs = writebuf.array();Buff.write(bs);Buff.flush();Buff.close();outSTr.close();ret = 0;} catch (Exception e) {e.printStackTrace();}return ret;}public static byte[] parseHexStr2Byte(String hexStr) {if (hexStr.length() < 1)return null;byte[] result = new byte[hexStr.length() / 2];for (int i = 0; i < hexStr.length() / 2; i++) {int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),16);result[i] = ((byte) (high * 16 + low));}return result;}/** * 输出字符串 * @param jsonString */public void write(String jsonString){HttpServletResponse response = ServletActionContext.getResponse();response.setCharacterEncoding("UTF-8");try {response.getWriter().print(jsonString);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static String getPrimaryKey(){ SimpleDateFormat simpleDateFormat;  simpleDateFormat = new SimpleDateFormat("hhMMss");  Date date = new Date();  String str = simpleDateFormat.format(date);  Random random = new Random();  int rannum = (int) (random.nextDouble() * (999 - 100 + 1)) + 10;// 获取2位随机数  System.out.println(str+rannum);// 当前时间 return str+rannum;  //return str;}public static void main(String[] args) {System.out.println(getPrimaryKey());}}
上一篇:java多线程

下一篇:java注解

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表