阿里云上传文件到oss的一个工具类方法

package cn.ipoc.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by hwp on 2018/10/16
 */
public class UploadUtil {

//    private static String endpoint = "oss-cn-beijing.aliyuncs.com";
    private static String endpoint = "oss-cn-beijing-internal.aliyuncs.com";
    private static String accessKeyId = "LTAIN3cNOkcXp1uo";
    private static String accessKeySecret = "PAKuEa44OMTAd7WZgKK4vSjksNffvB";
    private static String bucketName = "ipoc-bupt";

    public static String handleUpload(HttpServletRequest request) throws FileNotFoundException, IOException {
        String url = ""; //获取返回的url
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload sfu = new ServletFileUpload(factory);
            try {
                List items = sfu.parseRequest(request);
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        ;
                    } else {
                        String name = item.getName();
                        String extName = name.substring(name.indexOf("."));
                        if (extName.equals(".png")||extName.equals(".PNG")||extName.equals(".uab")||extName.equals(".mp4")||extName.equals(".MP4")) {
                            long maxSize = 1024 * 1024 * 200;
                            if (item.getSize() < maxSize) {
                                UUID uuid = UUID.randomUUID();

                                OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

                                String fileName = uuid.toString() + extName;//获取文件名

                                InputStream inputStream = item.getInputStream();


                                if (!ossClient.doesBucketExist(bucketName)) {
                                    /*
                                     * Create a new OSS bucket
                                     */
                                    System.out.println("Creating bucket " + bucketName + "\n");
                                    ossClient.createBucket(bucketName);
                                    CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
                                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                                    ossClient.createBucket(createBucketRequest);
                                }


                                ossClient.putObject(new PutObjectRequest(bucketName, fileName, inputStream));
                                ossClient.setObjectAcl(bucketName, fileName, CannedAccessControlList.PublicRead);
                                ossClient.setObjectAcl(bucketName, fileName, CannedAccessControlList.Default);
                                @SuppressWarnings("deprecation")
                                Date expiration = new Date(2020, 11, 17);
                                URL url0 = ossClient.generatePresignedUrl(bucketName,fileName, expiration);
                                String url1 = url0.toString();
                                int k = url1.length();
                                String L = url1.substring(0,31);
                                String R = url1.substring(40,k);
                                url = L+R;
                                ossClient.shutdown();
                                inputStream.close();

                            }
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }catch (OSSException oe) {//如果删除异常,则根据内容打印异常原因
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                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());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
            }
        }
        return url;
    }

写上传的问题中遇到的问题:
1,开始上传的时候使用外网链接地址,上传速度受到ecs服务器的带宽限制,50M的文件上传很久,因为oss是全国区域的不是某一地区的,所以使用内网访问地址,上传速度上升。
2,本地测试不能使用内网地址,本地工程位于外网,不属于内网访问,使用内网地址上传不会报错,但前端收不到响应,因为后台接口因为网址问题失效;
3,使用内网的Endpoint上传文件,Object返回的url会带有内网的endpoint,但是使用线上web端访问该网址时访问不了,不知道跟ECS位于华北区域,oss是全国范围有没有关系?目前想到的解决方法是把返回的url中涉及到内网网址的internal去掉就可以正常访问。但是不清楚为什么上面那个访问不了。

你可能感兴趣的:(阿里云)