2014-04-29 42 views
1

我正在編寫上傳文件到OneDrive的程序,基於Cordova Windows 7與Visual Studio 2013(在Windows 8.1 Pro上)。從Win32 C++程序上傳文件到OneDrive(SkyDrive)

儘管通過POST方法傳輸文件可以做到,但對此資源不允許發生錯誤「request_method_invalid:HTTP方法'POST'。」回報。

根據official document,寫的是可以用POST方法上傳。如果這是正確的,那麼這個代碼中哪裏出錯?

* picojson是一個開源的JSON解析器。

wstring filePath = L"C:\\..\\test.jpg"; 
wstring dest = L"https://apis.live.net/v5.0/me/skydrive/files/test.jpg"; 


file = CreateFile(filePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
if (file == INVALID_HANDLE_VALUE) { 
    SendErrorMessage(data, CONNECTION_ERR, filePath, dest); 
    goto out; 
} 
file_size.LowPart = GetFileSize(file, &file_size.HighPart); 

inet = InternetOpen(L"Cordova", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); 
if (!inet) { 
    SendErrorMessage(data, CONNECTION_ERR, filePath, dest); 
    goto out; 
} 

// 1- Headers 
buf = new BYTE[CHUNK_SIZE]; 
ws = L"Content-Type: multipart/form-data; boundary=" + BOUNDARY; 
if (!HttpAddRequestHeaders(req, ws.c_str(), ws.size(), HTTP_ADDREQ_FLAG_ADD)) { 
    SendErrorMessage(data, CONNECTION_ERR, filePath, dest); 
    goto end_req; 
} 
for (picojson::object::iterator i = headers.begin(); i != headers.end(); i++){ 
    if (i->second.is<wstring>() == false) continue; 
    ws = i->first + L": " + i->second.get<wstring>(); // Authorization: Bearer (access_token) 
    if (!HttpAddRequestHeaders(req, ws.c_str(), ws.size(), HTTP_ADDREQ_FLAG_ADD)) { 
     SendErrorMessage(data, CONNECTION_ERR, filePath, dest); 
     goto out; 
    } 
} 

// 2- Contents 
// 2.1 Contents headers 
ws = L""; 
for (picojson::object::iterator i = params.begin(); i != params.end(); i++){ 
    if (i->second.is<wstring>() == false) continue; 
    ws += L"--" + BOUNDARY + L"\r\n"; 
     + L"Content-Disposition: form-data; name=\"" + i->first + L"\";\r\n\r\n" 
     + i->second.get<wstring>() + L"\r\n"; 
} 
ws += L"--" + BOUNDARY + L"\r\n" 
    + L"Content-Disposition: form-data; name=\"" + fileKey + L"\"; filename=\"" + fileName + L"\"\r\n" 
    + L"Content-Type: " + mimeType + L"\r\n\r\n"; 


int utf8_len = WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), -1, NULL, 0, NULL, NULL); 
utf8_text = new char[utf8_len + 10]; 
if (!WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), ws.size(), utf8_text, utf8_len + 10, NULL, NULL)) { 
    SendErrorMessage(data, CONNECTION_ERR, filePath, dest); 
    goto end_req; 
} 

回答

1

如果你想通過POST上傳你的目標位置應該是多部分主體中文件名的父文件夾。從example

POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN 

Content-Type: multipart/form-data; boundary=A300x 

--A300x 
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt" 
Content-Type: application/octet-stream 

Hello, World! 
--A300x-- 
+0

它的工作原理。在Windows Store應用程序中,由於錯誤的地址也是成功的,所以我沒有注意到。謝謝! – Tank2005

2

這就是說,它實際上是一個更容易使用PUT文件上傳。在這種情況下,上面指定的路徑是正確的(即文件名屬於路徑),並且您可以將文件的內容按原樣寫入響應主體。

相關問題