2017-05-25 06:09
浏览 49


I want to copy a file from the client to the server through the rest end point exposed by the server. I referred the various questions and answers in stackoverflow but I could not get a clear picture of it.

I just want a sample client and server code in golang to copy the file from client and save it on the server.

Thanks in advance.

图片转代码服务由CSDN问答提供 功能建议

我想通过服务器公开的其余端点将文件从客户端复制到服务器。 我在stackoverflow中提到了各种问题和答案,但我对此一无所知。



  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutong6814 2017-05-25 07:56

    Direction: Server to Client

    So -- both sides are in Go? Okay, let's start with the server side. See my WebLoad.go file from my CSVStorageServer server: (Link to Github)

    At line 17, I define the handler for the web server. This method will build a zip file on-demand and send it to the browser. The important part regarding to your question are line 77 up to 82. Here, I set the headers for the client, e.g. content length and type. Line 82 sends the whole data to the client side. It copies the bytes from the on-demand zip file to the wire.

    On the client side, you trigger e.g. a GET request and store the result. Here an example: https://golang.org/pkg/net/http/#example_Get

    With http.Get(... you trigger the GET request. With ioutil.ReadAll(res.Body) you read all bytes from the server and store it to a variable. Afterwards, you could write the bytes to the disk or process it in-memory.

    I hope, this answer helps you.

    Best regards, Thorsten

    Edit #1: Regarding the REST end-point, cf. the server definition (link to Github). Line 16 defines the REST end-point for this handler. In this case, it gets available as /load. You could use any REST-like path here, e.g. /open/file/USERID/send, etc.

    Direction: Client to Server

    In order to copy a file from client to server side, similar operations are necessary. On the client side, a POST request is necessary as multipart/form-data. Here is a good example for this: Link to a blog post. This example considers also the server part. The relevant client part is the function func postFile(filename string, targetUrl string) error { ... }.

    For the server part, here an own example: Link to Github. This example receives an file from the client and writes it to a MongoDB database. The relevant parts are:

    Line 39 read the file from the client: file, fileHeader, fileError := request.FormFile("file") The result is a handle to this uploaded file.

    Line 60 copies all bytes from the source (browser or Go client) into a destination (here, the MongoDB): _, errCopy := io.Copy(newFile, file).

    Edit #2:

    Here is a full working example: https://github.com/SommerEngineering/Example010 where client and server are in the same program. It should be easy to split it into two programs.

    点赞 评论

相关推荐 更多相似问题