上传文档至 COS

... 2022-7-27 大约 1 分钟

# 上传文档至 COS

调用方执行预导入操作后,需要调用 HTTP 协议的 PUT 方法向 腾讯云 COS (opens new window) 上传文件。

向 COS PUT 文件成功后无响应结果。

本示例给出了如下几种语言向腾讯云 COS 上传文件的代码。

# Golang

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
)

/*
   需要用到 upload-url 接口的返回值:
   COSPutURL
*/

func main() {
	file := "/root/data/example.docx"
	r, err := ioutil.ReadFile(file)
	if err != nil {
		fmt.Println(err)
		return
	}
	COSPutURL := "https://docs-import-export.cos.ap-guangzhou.myqcloud.com/exampl.docx?xxx"
	req, err := http.NewRequest(http.MethodPut, COSPutURL, bytes.NewReader(r))
	if err != nil {
		fmt.Println(err)
		return
	}
	// 根据预导入文档接口返回的CustomHeader设置header
    customHeaders := map[string]string{
		"Content-Type": "application/pdf",
		"x-cos-acl":    "default",
	}
	// Add custom headers to the request
	for key, value := range customHeaders {
		req.Header.Add(key, value)
	}
	client := &http.Client{}
	_, err = client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

# Java

package main;

import java.io.File;
import java.io.IOException;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

/*
   需要用到 upload-url 接口的返回值:
   COSPutURL
*/

public class CosUploadFile {
    public static void main(String[] args) throws IOException {
        File file = new File("/root/data/example.docx"); // 上传的文件
        OkHttpClient client = new OkHttpClient();
        // 根据预导入文档接口返回的CustomHeader设置header
        Map<String, String> customHeaders = new HashMap<>();
        customHeaders.put("Content-Type", "application/pdf");
        customHeaders.put("x-cos-acl", "default");
        String contentType = customHeaders.get("Content-Type");
        MediaType mediaType = MediaType.parse(contentType);
        RequestBody body = RequestBody.create(mediaType, file);
        Request.Builder requestBuilder = new Request.Builder()
                .url("https://docs-import-export.cos.ap-guangzhou.myqcloud.com/exampl.docx?xxx") // COSPutURL
                .put(body);
        for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
            requestBuilder.addHeader(entry.getKey(), entry.getValue());
        }
        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# Python

import requests


# 需要用到 upload-url 接口的返回值 : COSPutURL
def put_file(url, header, file):
    with open(file, 'rb') as f:
        try:
            response = requests.put(url, headers=header, data=f)
        except Exception as e:
            print(str(e))
    return response


if __name__ == '__main__':
    file = '/root/data/example.docx'
    # 根据预导入文档接口返回的CustomHeader设置header
    custom_headers = {
        "Content-Type": "application/pdf",
        "x-cos-acl": "default"
    }
    COSPutURL = 'https://docs-import-export.cos.ap-guangzhou.myqcloud.com/exampl.docx?xxx'
    res = put_file(COSPutURL, custom_headers, file)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
上次编辑于: 2025年5月9日 18:23
贡献者: muyanyang , mylochen , daleshen , livlin