阿里云OSS通过URL上传文件

来源:互联网 发布:php smarty 编辑:程序博客网 时间:2024/05/22 00:45

网上有很多教程都看的不太懂,自己瞎琢磨了大半天终于给自己给琢磨出来了,在这里记录下大笑

我后台接收的是个url,开始上传至阿里云的时候测试下上传的路径,发现上传的文件都有问题,图片只显示一部分,音频不播放,我在想是不是丢包了。。。后来查资料看到有人说阿里云好像并不支持url上传。所以最后只能先把url的内容下载到本地,然后通过本地去上传。

上代码:

package com.fh.util;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;


import com.aliyun.oss.OSSClient;
import com.fh.controller.mobile.utils.OssUtil;


public class DownLoadImg {


public static void main(String[] args) {
OSSClient ossClient = OssUtil.getOssClient();
String downImgPath="http://img.my.csdn.net/uploads/201508/05/1438760757_3588.jpg";//图片地址
String[] strArray = downImgPath.split("\\.");//为了获取图片的后缀,这样可以使方法不仅仅只能上图片了
String path="E:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/FM952/static/downImgAndAudio";//下载的地址
String  name = "downImg";
        File dir = new File(path);
        if(!dir.exists())
             dir.mkdir();                                                /*如果目录不存在则创建目录*/
        path += name + "."+strArray[strArray.length-1];
DownLoadImg.download(downImgPath, path);//将文件下载
String filePath="E:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/FM952/static/downImgAndAudio"+name+"."+strArray[strArray.length-1];
OssUtil.uploadFileOSS(ossClient, new File(filePath.replaceAll("\\\\", "/")), "fm952", "uploadFiles/file/");
}

public static void download(String strUrl,String path){
  URL url = null;
  try {
         url = new URL(strUrl);
  } catch (MalformedURLException e2) {
        e2.printStackTrace();
        return;
  }
  InputStream is = null;
       try {
           is = url.openStream();
       } catch (IOException e1) {
           e1.printStackTrace();
           return;
       }
       
       OutputStream os = null;
       try{
           os = new FileOutputStream(path);
           int bytesRead = 0;
           byte[] buffer = new byte[8192];
           while((bytesRead = is.read(buffer,0,8192))!=-1){               /*buffer数组存放读取的字节,如果因为流位于文件末尾而没有可用的字节,则返回值-1,以整数形式返回实际读取的字节数*/
           os.write(buffer,0,bytesRead);
      }
      }catch(FileNotFoundException e){
          e.printStackTrace();
          return;
      } catch (IOException e) {
          e.printStackTrace();
          return;
     }
}
}


package com.fh.controller.mobile.utils;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.fh.util.DateUtil;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;


/**
 * Created by AB on 2016/9/6.
 */
public class OssUtil {


    private static final Logger LOG = Logger.getLogger(OssUtil.class);
    private static final String endpoing = "oss-cn-hangzhou.aliyuncs.com";


    private static final String accessKeyId = "LTAIYZFnuu9q5x4l";
    private static final String accessKeySecret = "VGaW6B1X2Ocaq0rgicl1q501IJnYSa";


    public static final OSSClient getOssClient() {
        return new OSSClient(endpoing, accessKeyId, accessKeySecret);
    }
    
    public static final String uploadFileOSS(OSSClient client, File file, String bucketName, String diskName){
    String resultStr = null;
        String key = null;
        if (file!=null) {
        try {
        InputStream is = new FileInputStream(file);
            String fileName = file.getName();
            Long fileSize = file.length();
            String suffix = fileName.substring(fileName.lastIndexOf('.'));
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            fileName = UUID.randomUUID().toString().trim().replaceAll("-", "").toLowerCase() + suffix;
            key = diskName + DateUtil.getDays() + '/' + fileName;
            //上传文件
            PutObjectResult putResult = client.putObject(bucketName, key, is, metadata);
            //解析结果
            resultStr = putResult.getETag();
            return "http://fm952.oss-cn-hangzhou.aliyuncs.com/" + key;
        } catch (Exception e) {
            LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        } 
}
        return null;
    }

}

思路就是这样了。