HTML5之跨域请求上传文件到OSS

CORS协议:

  1.COR请求的分类:

      1.简单的COR请求,直接向跨域资源发送请求,包含简单的头和方法.返回的头部信息包含Access-Control-Allow-Origin:www.helloword.com.代表www.helloword.com域名跨域访问.

      2.复杂的COR包含复杂的方法和头,它需要先发送预请求,允许才能发送真实请求

  2.回复的请求头信息的含义

      1.Access-Control-Allow-Origin: http://haha.com.代表允许跨域的域名 *代表所有的域名都跨域跨域

      2.Access-Control-Max-Age: 60,代表在60秒内不需要发送预请求,缓存该结果

      3.Access-Control-Allow-Methods: GET,PUT代表允许get,和put的请求跨域

      4.Access-Control-Allow-Headers: content-type代表允许跨域请求携带context-type信息()

  3.代码

      1.引入tomcat对cor支持的jar包(简单COR请求不需要)CorsFilter过滤器源码分析见(http://www.cnblogs.com/2nao/p/7263977.html)

      <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-catalina</artifactId>
        <version>7.0.78</version>
        <scope>provided</scope>
      </dependency>

      2.配置web.xml

      <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
      </filter>

      <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>

      3.上传文件代码

  public @ResponseBody
    JSONObject upload(MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
        String requestUrl= URLUtils.getUrl(request);//设置允许访问的白名单
        if(requestUrl == null){//访问者不在白名单里面,返回null
            return null;
        }

        log.info("上传文件start");

        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String key = random.nextInt(10000) + System.currentTimeMillis() + substring;

        try {
            PutObjectResult por = client.putObject(bucketName, key, new ByteArrayInputStream(file.getBytes()));
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            // 生成URL
            URL url = null;
            try {
                url = client.generatePresignedUrl(bucketName, key, expiration);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                client.shutdown();
            }
            if (url != null) {
                String urlStr = url.toString();

                if (!urlStr.contains(EXPIRES)) {
                    JsonSettingUtils.setException(jsonObject);
                    log.info("生成文件url失败:url中不包含?Expires字符串");
                    return jsonObject;
                }

                urlStr = urlStr.substring(0, urlStr.indexOf(EXPIRES));
                data.put("url", urlStr);
                response.setHeader("Access-Control-Allow-Origin",requestUrl);//设置跨域允许所有的域名跨域
                                            //设置*会存在,设置跨域的cookie,带不到要跨域的服务端. } } catch (Exception e) { log.error("文件上传失败"); JsonSettingUtils.setException(jsonObject); return jsonObject; } log.info("上传文件end"); JsonSettingUtils.setSuccessAndData(jsonObject, data); return jsonObject; }

 

 

public class URLUtils {
    /**
     * 获取访问者的域名
     * @param request
     * @return
     */
    public static String getUrl(HttpServletRequest request){

       
String url= request.getHeader("Referer");
if (url == null){
return null;
}

Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");

Matcher m = p.matcher(url);

if(m.find()){
url= m.group();
}
log.info("获取访问者的请求:{}",url );
for (String string : ConstantUtils.URLS) {
if (string.equals(url)) {
return string;
}
}
return null;
} }

 

posted @ 2017-07-10 20:15  我_会飞的鱼  阅读(839)  评论(0编辑  收藏  举报