簡體   English   中英

具有應用程序/八位字節流的Spring Boot multipartFile引發異常

[英]spring boot multipartFile with application/octet-stream throws exception

我想使用Spring Boot構建一個簡單的Rest api,該api接受任何給定的文件,然后對其執行一些操作。 我瀏覽了multipartFile https://spring.io/guides/gs/uploading-files/上的spring示例,並決定采用相同的方法。 通過我的rest api上傳的文件將具有一些特定的擴展名。 因此,我將內容類型指定為application / octet-stream。 當我嘗試以相同的方式運行單元測試用例時,總是會遇到以下例外:

nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request

如果內容類型為text / plain或requestMapping中沒有“ consumes”參數,則不會出現此異常。

我的控制器代碼如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/v1/sample")
public class SampleController {

    private static Logger log = LoggerFactory.getLogger(SampleController.class);

    @RequestMapping(path = "/{id}/upload",
                    consumes = {MediaType.APPLICATION_OCTET_STREAM_VALUE},
                    method = RequestMethod.POST)
    public ResponseEntity<String> uploadfile(@PathVariable String id,
            @RequestParam("file") MultipartFile upgradeFile) {
        log.info("Obtained a upload request for the id {}",id );
        return new ResponseEntity<String>("file upload has been accepted.",
                HttpStatus.ACCEPTED);
    }

}

我的單元測試片段如下:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.stellapps.devicemanager.fota.Application;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = Application.class)
@EnableWebMvc
public class ControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void mockMvcBuilder() {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
        public void test_ValidPayload() {
            String uri = "/v1/sample/1234/upload";
            Path path = Paths.get("src/test/resources/someFile");
            try {
                byte[] bytes = Files.readAllBytes(path);
                 MockMultipartFile multipartFile =
                            new MockMultipartFile("file", "someFile.diff", "application/octet-stream", bytes);
                 mockMvc.perform(fileUpload(uri).file(multipartFile).contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
                    .andExpect(status().isAccepted());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

如果我使用text / plain作為內容類型,並且給出普通的文本文件,則可以正常進行。 如果我將內容類型添加為application / octet-stream,則會引發以下異常

    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.web.multipart.MultipartException: The current request is not a multipart request
    at org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.assertIsMultipartRequest(RequestPartMethodArgumentResolver.java:204)
    at org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:129)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:99)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)

如何使我的請求接受應用程序/八位字節流,以及應該對測試用例進行哪些更改以確保其成功。

更新:

刪除消耗標頭並通過在MockPartFile中未指定內容類型是上載文件的方法之一。 我想默認情況下控制器將其作為application / octet-stream

更新:

感謝您的答復。 我使用的是早期版本的spring(1.3.1),經過回答后,我更新了spring版本和測試用例以使其匹配,然后它開始工作。

請嘗試以下步驟

  • 從RequestMapping屬性中刪除消耗
  • MockMultipartFile multipartFile = new MockMultipartFile("file","somename","multipart/form-data", fileinputstream);
  • 更改為MockMvc:

     mockMvc.perform(MockMvcRequestBuilders.fileUpload("/v1/sample/1234/payload") .file(multipartFile) .andExpect(status().isOk()); 

如需幫助,請檢查使用Spring mvc和MockMVC上傳文件

編輯:

我已經嘗試了一個適合您的方案的示例spring-boot-rest應用。 似乎application / octet-stream沒問題。 請檢查我的倉庫https://github.com/satya-j/boot-file-manager

暫無
暫無

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

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