How to parse multipart/form-data?

问题: I have a server written in Go. Basically, it receives POST-request and sends some file in response as multipart/form-data. Following is the server code: func ColorTransf...

问题:

I have a server written in Go.
Basically, it receives POST-request and sends some file in response as multipart/form-data.
Following is the server code:

func ColorTransferHandler(w http.ResponseWriter, r *http.Request) {
    ... some routine...

    w.WriteHeader(http.StatusOK)

    mw := multipart.NewWriter(w)

    filename := "image_to_send_back.png"

    part, err := mw.CreateFormFile("image", filename)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    local_file, err := os.Open(filename)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    local_file_content, err := ioutil.ReadAll(local_file)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    part.Write(local_file_content)

    w.Header().Set("Content-Type", mw.FormDataContentType())

    if err := mw.Close(); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

}

Client code in Java for Android:

public class ConnectionUtility {
    private final String boundary;
    private static final String LINE_FEED = "rn";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    public List<String> finish() throws IOException {
        // ...
        // content filling
        // ...

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        List<String> response = new ArrayList<String>();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }

Following are my questions:
1. How do I edit this function to get that image file and save it on a drive?
2. Probably I can use some libraries to do this?

Help will be appreciated


回答1:

First of all I suggest you to use wrapper libraries for managing network connections, as far as it requires some experience to handle them in the right way. I don't you suggest manually crafting multipart request using HttpURLConnection

Android

You can try to use OkHTTP or even Retrofit, if you don't want to manually configure the connection.

OkHTTP

Here is a basic example, I have omitted some parts like exception handling. Also please note you don't need to create the client for every call.

OkHttpClient client = new OkHttpClient.Builder().build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
       .addFormDataPart("image_file", imageFileName, RequestBody.create(
        MediaType.parse("image/jpeg"), new File(pathToImage)));
        .addFormDataPart("anyOtherFormArg", arg1) 
        .addFormDataPart("anotherArg", arg2)
        .build();
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
result = response.body().string();

Retrofit

Retrofit just wraps underlying network requests with a pretty interface

@Multipart
@POST("endpoint/image")
Observable<ResponseBody> uploadImage(@Part("arg1") RequestBody arg1,
                                       @Part MultipartBody.Part image);

Go Server

On the server side you can try to use

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        err := r.ParseMultipartForm(32 << 20) // 32MB max upload size
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        m := r.MultipartForm
        var file_name string
        file, handler, err := r.FormFile("image_file")//get file 
        defer file.Close() //close the file when we finish
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        f, err := os.OpenFile("/path_to_save_image/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        file_name = handler.Filename
        defer f.Close()
        io.Copy(f, file)

        //return something
        w.Header().Set("Content-Type", "application/json")
        w.Write("success")
        w.WriteHeader(200)
    }
    w.Header().Set("Content-Type", "application/json")
    w.Write("error")
    w.WriteHeader(400)
}

This just a basic example, try to undertand each part and tune it as required.

  • 发表于 2019-02-18 14:25
  • 阅读 ( 1071 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除