尝试使用Spring MVC 6.0.6编写一个简单的文件上传处理程序。使用POST
上传文件,编码为multipart/form-data
。在服务器端,处理程序是
import jakarta.servlet.annotation.MultipartConfig;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@MultipartConfig
public class SimpleUpload {
@PostMapping(path = "/upload")
public ResponseEntity<String> uploadFile(@RequestParam("File") MultipartFile file) {
return file.isEmpty() ?
new ResponseEntity<String>(HttpStatus.NOT_FOUND) : new ResponseEntity<String>(HttpStatus.OK);
}
}
获取此错误:Unable to process parts as no multi-part configuration has been provided
。
我已经阅读了关于此错误的其他答案,因此我添加了多部分配置,如下所示:
@EnableWebMvc
@Configuration
@Import({ApplicationConfig.class})
public class MvcConfig implements WebMvcConfigurer {
@Bean(name = "multipartResolver")
public MultipartResolver getMultipartResolver() {
return new StandardServletMultipartResolver();
}
@Bean(name = "filterMultipartResolver") // alternate name suggested by some people
public MultipartResolver getFilterMultipartResolver() {
return new StandardServletMultipartResolver();
}
}
它似乎不起作用,因为错误总是一样的。
应用程序中的单元测试成功:
@WebAppConfiguration
@ContextConfiguration(classes = { MvcConfig.class, SimpleUpload.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class MultipartPostRequestControllerUnitTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Test
public void whenFileUploaded_thenVerifyStatus() throws Exception {
MockMultipartFile file = new MockMultipartFile("File",
"hello.txt",
MediaType.TEXT_PLAIN_VALUE,
"Hello, World!".getBytes());
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
mockMvc.perform(multipart("/upload")
.file(file))
.andExpect(status().isOk());
}
}
但是通过Postman向http://127.0.0.1:8080/upload发送文件会返回HTTP状态500,根本原因是Unable to process parts as no multi-part configuration has been provided
。
我该怎么解决这个问题?
使用Tomcat 10.1.7运行应用程序。
1条答案
按热度按时间yyyllmsg1#
由于您已经移动到spring 6,因此它将使用
jakarta.servlet-api
。另外,您已经使用了spring-mvc,因此必须在web.xml文件中进行配置,以让servlet知道它需要支持multipart请求。@MultipartConfig
不能与web.xml一起使用。StandardServletMultipartResolver
需要1个bean。您需要更新
web.xml
添加<multipart-config />