英文:
How can I upload a file to server, without browser, using go?
问题
trsp := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
Url := "https://127.0.0.1:8080"
client := &http.Client{Transport: trsp}
request, _ := http.NewRequest("POST", Url, nil)
k, _ := os.Open(nameOfFile)
request.Header.Set("Action", "download"+k.Name())
...
...
client.Do(request)
我有一个服务器,我需要将文件上传到服务器。我应该如何处理请求?我认为我应该将文件写入request.Body,然后在服务器端处理这个请求。
英文:
trsp := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
Url := "https://127.0.0.1:8080"
client := &http.Client{Transport: trsp}
request, _ := http.NewRequest("POST", Url, nil)
k, _ := os.Open(nameOfFile)
request.Header.Set("Action", "download"+k.Name())
...
...
client.Do(request)
I have server, and I need to upload to server a file. What should I do with request? As I think I shoud write into request.Body and then, from server handle this query
答案1
得分: 2
你需要使用"mime/multipart"
包来创建HTTP请求的请求体,就像这样。
http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
return http.NewRequest("POST", uri, body)
}
英文:
you need use the "mime/multipart"
package to make the http body. like this.
http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
return http.NewRequest("POST", uri, body)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论