如何使用office365 rest api将文件上传到sharepoint?

时间:2014-11-30 04:40:38

标签: ruby-on-rails ruby rest office365

我使用以下ruby代码将文件上传到Office 365

uri = URI.parse("#{site_url}/_api/v1.0/me/files/#{folder}/children/#{temp_file.original_filename}/content")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true

req = Net::HTTP::Put.new(uri.path, initheader = {
   'Content-Type' =>'application/octet-stream', 
   'Authorization' => 'Bearer ' + @current_user.o_auth_token,
   'resource' => 'site_url'
})

req.set_form_data(
                  'file' => temp_file.read, 
                  'Content-Type' => 'application/octet-stream'
                 )

JSON.parse(https.request(req).body)

上传到office 365的文件已损坏。代码中的问题是什么?

1 个答案:

答案 0 :(得分:0)

PHP中的以下代码可以正常工作。请注意这些是类中的函数,还需要创建一个SharepointException类。

public function upload_file($folder_id, $filepath, $filename) {
    //remove illegal characters form filename
    try {
        $filename = $this->clean_filename($filename);
    } catch (SharepointException $e) {
        throw new SharepointException($e->getMessage());            
    }

    //build uri
    if (is_null($folder_id)) {
        $uri = $this->base_url . 'files/root/children/'.rawurlencode($filename).'/content?nameConflict=abort';            
    } else {
        $uri = $this->base_url . 'files/'.$folder_id.'/children/'.rawurlencode($filename).'/content?nameConflict=abort';            
    }

    $response = $this->upload($uri, $filepath);        
    if (array_key_exists('error', $response)) {
        throw new SharepointException($response['error']);
    }

    return $response;        
}

private function upload($uri, $filepath) {
    $pointer = fopen($filepath, 'r+');
    $stat = fstat($pointer);
    $pointersize = $stat['size'];
    $ch = curl_init($uri);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_INFILE, $pointer);
    curl_setopt($ch, CURLOPT_INFILESIZE, (int)$pointersize);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);

    //Expect: 
    //HTTP response code 100 workaround
    //see http://www.php.net/manual/en/function.curl-setopt.php#82418
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Expect:',
        'Content-Type: application/json',
        'Authorization: Bearer ' . $this->access_token,
    ));

    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);     

    $accepted_codes = array(
        '200',
        '201',
    );        

    if (!in_array($httpcode, $accepted_codes)) {    
        //generic error
        $error = 'HTTP status code not expected - got '.$httpcode;
        //more descriptive error
        if ($httpcode == '400') {
            $data = json_decode($response, true);
            if (isset($data['error']['message'])) {
                $error = $data['error']['message'];
            }
        }
        return array('error' => $error);
    }
    return json_decode($response, true);          
}

private function clean_filename($filename) {
    $filename = preg_replace('/[*><|}{&#%~:"?\/\\\\]/', '', $filename);
    if (strpos('.', $filename) === 0) {
        $filename = substr($filename, 1);
    }

    if (empty($filename)) {
        throw new SharepointException('File is empty after removing illegal characters.');
    }

    return $filename;
}