duanba8070 2019-02-16 09:12
浏览 1142

如何解析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 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 = "
";
    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条回答 默认 最新

  • duanmengsuo9302 2019-02-16 10:40
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧