簡體   English   中英

如何在使用RestTemplate(來自其他客戶端)時為分段上傳中的文件設置內容類型

[英]How to set content-type for the file in multipart upload when using RestTemplate (from a rest client)

我正在嘗試上傳的文件將始終是一個xml文件。 我想將content-type設置為application / xml這是我的代碼:

         MultiValueMap<String, Object parts = new LinkedMultiValueMap<String,
         Object(); parts.add("subject", "some info"); 
         ByteArrayResource xmlFile = new    ByteArrayResource(stringWithXMLcontent.getBytes("UTF-8")){
                 @Override
                 public String getFilename(){
                     return documentName;
                 }             
             };

     parts.add("attachment", xmlFile);

//sending the request using RestTemplate template;, the request is successfull 
String result = template.postForObject(getRestURI(), httpEntity,String.class);      
//but the content-type of file is 'application/octet-stream'

原始請求如下所示:

    Content-Type:
    multipart/form-data;boundary=gbTw7ZJbcdbHIeCRqdX81DVTFfA-oteHHEqgmlz
    User-Agent: Java/1.7.0_67 Host: some.host Connection: keep-alive
    Content-Length: 202866

    --gbTw7ZJbcdbHIeCRqdX81DVTFfA-oteHHEqgmlz Content-Disposition: form-data;    name="subject" Content-Type: text/plain;charset=ISO-8859-1
    Content-Length: 19

    some info

    --gbTw7ZJbcdbHIeCRqdX81DVTFfA-oteHHEqgmlz Content-Disposition: form-data;   name="attachment"; filename="filename.xml" Content-Type:
    application/octet-stream Content-Length: 201402

    ....xml file contents here ..

文件的內容類型生成為'application / octet-stream',我希望它是'application / xml'我如何設置文件的內容類型?

我從這個鏈接中獲取提示后想出了解決方案:

使用帶有spring for android的壓縮jpeg字節數組進行多部分發布請求

解決方法是將ByteArrayResource放在帶有必需頭的HttpEntity中,並將HttpEntity添加到Multivaluemap(而不是添加ByteArrayResource本身。)

碼:

Resource xmlFile = new ByteArrayResource(stringWithXMLcontent.getBytes("UTF-8")){
            @Override
            public String getFilename(){
                return documentName;
            }
        };
        HttpHeaders xmlHeaders = new HttpHeaders();
        xmlHeaders.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<Resource> xmlEntity = new HttpEntity<Resource>(xmlFile, xmlHeaders);
        parts.add("attachment", xmlEntity);

我沒有使用RestTemplate,但我過去使用過HttpClient - 這就是我傳遞身體部位的方法 -

MultipartEntityBuilder eb = MultipartEntityBuilder.create().setBoundary(MULTIPART_BOUNDARY)
                .addTextBody(BODYPART_ENTITY, key, ContentType.create("application/xml", Charset.forName("UTF-8")));

您將不得不在RestTemplate中查看可以采用內容類型的API

由於我無法評論@RGR的答案,我將此作為新答案發布,盡管RGR的答案絕對正確。

問題是,Sprint RestTemplates使用FormHttpMessageConverter發送多部分請求。 此轉換器檢測從Resource繼承的所有內容,並將其用作請求的“文件”部分。 例如,如果您使用MultiValueMap,只要添加“資源”,您添加的每個屬性都將在其自己的部分中發送...-->設置文件名,Mime-Type,length,..將不會成為“檔案部分“。

不是答案,但它解釋了為什么必須擴展ByteArrayResource以返回文件名並作為請求的唯一部分發送。 發送多個文件將適用於MultiValueMap

SPR-13571在Spring 4.3中修復了這種行為

暫無
暫無

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

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