上传多文件及数据安卓端及go语言后台端接收

1. android端代码

public interface GetData {

 @POST("upload")
 Observable upload(@Body RequestBody Body);

}
 Retrofit  retrofit = new Retrofit.Builder()
                .baseUrl("http://10.0.3.28:8080/")
 GetData request = retrofit.create(GetData.class);

 File file = new File(path);
        //构建body
        //addFormDataPart()第一个参数为表单名字,这是和后台约定好的
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "name")
                .addFormDataPart("phone", "phone");
        //注意,file是后台约定的参数,如果是多图,file[],如果是单张图片,file就行
        for (int i=0;i<3;i++) {
            //这里上传的是多图
            builder.addFormDataPart("files", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        }
        RequestBody requestBody = builder.build();
        Observable observable = request.upload(requestBody);
        observable
                .subscribeOn(Schedulers.io())           //在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())//回到主线程处理请求结果
                .subscribe(new Subscriber() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("lsm", "Throwable == " + e.toString());
                    }

                    @Override
                    public void onNext(String s) {
                        Log.d("lsm", "result == " + s);
                    }
                });


2. Go语言后端代码

package main


import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    r := gin.Default()
    r.POST("/upload", func(c *gin.Context) {
        // Multipart form
        form, e1 := c.MultipartForm()
        if e1!=nil {
            fmt.Println(e1)
        }
        usernames := form.Value["username"]  //数据切片
        fmt.Printf("username == %s\n",usernames[0])

        files := form.File["files"] //文件切片
        for a, file := range files {
            fmt.Println(file.Filename)
            fmt.Printf("a == %d\n",a)
            // 上传文件至指定目录
            c.SaveUploadedFile(file, "F:/image/"+file.Filename)
        }
        c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
    })
        r.Run(":8080") // 监听并在 :8080 上启动服务

你可能感兴趣的:(上传多文件及数据安卓端及go语言后台端接收)