簡體   English   中英

如何解析multipart / form-data?

[英]How to parse multipart/form-data?

我有一個用Go編寫的服務器。
基本上,它接收POST請求並作為multipart / form-data發送一些文件作為響應。
以下是服務器代碼:

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
    }

}

適用於Android的Java客戶端代碼:

public class ConnectionUtility {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    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;
    }

以下是我的問題:
1.如何編輯此功能以獲取該圖像文件並將其保存在驅動器上?
2.也許我可以使用一些庫來做到這一點?

幫助將不勝感激

首先,我建議您使用包裝器庫來管理網絡連接,因為需要一些經驗才能以正確的方式處理它們。 我不建議您使用HttpURLConnection手動制作multipart請求

安卓系統

如果您不想手動配置連接,則可以嘗試使用OkHTTP或什至Retrofit

好的HTTP

這是一個基本示例,我省略了某些部分,例如異常處理。 另外請注意,您不需要為每個呼叫都創建客戶端。

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();

翻新

改造僅通過一個漂亮的界面來包裝基礎網絡請求

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

去服務器

在服務器端,您可以嘗試使用

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)
}

這只是一個基本示例,請嘗試理解每個部分並根據需要對其進行調整。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM