1. 程式人生 > >關於上傳文件的跨域問題

關於上傳文件的跨域問題

res xmlhttp 跨域訪問 wex5 option XML ken char ext

在進行新框架開發的過程中,需要自定義頁面組件實現脫離表單的文件(圖片)上傳,考慮過wex5自帶的attachmentsimple的自定義寫法很難受,就改用了第三方插件webuploader來實現選擇文件後調用服務端的上傳文件接口實現自動上傳。

中間遇到過跨域問題,即服務端所在接口域名與插件包(前端)不在同一域名下,但是由於格式是文件,所以必須采用post傳輸方式

解決方法:

利用CORS實現POST方式跨域請求數據

CORS全名Cross-Origin Resource Sharing,顧名思義:跨域分享資源,這是W3C制定的跨站資源分享標準。

目前包括IE10+、chrome、safari、FF都提供了XMLHttpRequest對象對該標準的支持,在更老的IE8中則提供了xDomainRequest對象,部分實現了該標準;

在利用XMLHttpRequest對象發POST請求前會發一個options嗅探來確定是否有跨域請求的權限;同時在header頭上帶上Origin信息來指示來源網站信息,服務器響應時需要帶上Access-Control-Allow-Origin頭的值是否和Origin信息相匹配。

header("Access-Control-Allow-Origin: http://localhost"); // *為全部域名

CORS的缺點是你必須能控制服務器端的權限,允許你跨域訪問

設置CORS實現跨域請求

一、使用php代碼實現(寫在接口開始位置)


$request_method = $_SERVER[‘REQUEST_METHOD‘];

if ($request_method === ‘OPTIONS‘) {

header(‘Access-Control-Allow-Origin:‘.$origin);
header(‘Access-Control-Allow-Credentials:true‘);
header(‘Access-Control-Allow-Methods:GET, POST, OPTIONS‘);

header(‘Access-Control-Max-Age:1728000‘);
header(‘Content-Type:text/plain charset=UTF-8‘);
header(‘Content-Length: 0‘,true);

header(‘status: 204‘);
header(‘HTTP/1.0 204 No Content‘);

}

if ($request_method === ‘POST‘) {

header(‘Access-Control-Allow-Origin:‘.$origin);
header(‘Access-Control-Allow-Credentials:true‘);
header(‘Access-Control-Allow-Methods:GET, POST, OPTIONS‘);

}

if ($request_method === ‘GET‘) {

header(‘Access-Control-Allow-Origin:‘.$origin);
header(‘Access-Control-Allow-Credentials:true‘);
header(‘Access-Control-Allow-Methods:GET, POST, OPTIONS‘);

}


二、使用nginx配置實現


location / {

set $origin ‘*‘;

if ($request_method = ‘OPTIONS‘) {

add_header ‘Access-Control-Allow-Origin‘ $origin;

#
# Om nom nom cookies
#
add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;

#
# Custom headers and headers various browsers *should* be OK with but aren‘t
#
add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘;

#
# Tell client that this pre-flight info is valid for 20 days
#
add_header ‘Access-Control-Max-Age‘ 1728000;
add_header ‘Content-Type‘ ‘text/plain charset=UTF-8‘;
add_header ‘Content-Length‘ 0;

return 204;

}

if ($request_method = ‘POST‘) {

add_header ‘Access-Control-Allow-Origin‘ $origin;
add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘;

}

if ($request_method = ‘GET‘) {

add_header ‘Access-Control-Allow-Origin‘ $origin;
add_header ‘Access-Control-Allow-Credentials‘ ‘true‘;
add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
add_header ‘Access-Control-Allow-Headers‘ ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type‘;

}

}

關於上傳文件的跨域問題