Spring 6下的文件上传问题

问题描述 投票:0回答:1

我是 Spring 框架的新手,在 Spring 6 中遇到文件上传问题。根据一些教程视频,以下代码应该与 commons-fileupload 一起在 spring 5 下工作。但根据这个问题

org.springframework.web.multipart.commons.CommonsMultipartResolver
在 Spring 6 中不再可用。因此,我根据 文档 使用了另一个解析器。但问题是
multipartFile
photo
都为空。我还尝试将
@RequestParam("photo")
@RequestPart("photo")
添加到
MultipartFile photo
,似乎处理程序未到达,因为根本没有打印。

这是带有 thymeleaf 语法的 html 表单。

<form  th:action="@{/uploadFile}" enctype="multipart/form-data" method="post">
    <div>
        <label for="photo">Choose a file to upload:</label>
        <input type="file" id="photo" name="photo">
    </div>
    <br>
    <div>
        <button type="submit">Upload</button>
    </div>
</form>

这是处理方法和解析器 bean。

    // I also tried using xml-based configuration, but it did not work
    @Bean
    public StandardServletMultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String testUpload(HttpServletRequest request, MultipartFile photo, HttpSession session) throws IOException {
        System.out.println("MultipartFile: " + photo);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("photo");
        System.out.println("multipartRequest.getFile(\"photo\"): " + multipartFile);
        String fileName = photo.getOriginalFilename();
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + hzName;
        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);
        if (!file.exists()) {
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + fileName;
        photo.transferTo(new File(finalPath));
        return "success";
    }

搜索了文档和其他相关问题。

spring spring-mvc
1个回答
0
投票

抱歉英语不好。

org.springframework.web.multipart.commons.CommonsMultipartResolver
在 Spring 6 中不再可用。您可以使用
StandardServletMultipartResolver
类。

为了在 Servlet 3.0 中上传文件,我们需要配置应用程序的几个部分 -:
第 1 步:
为了解析多部分请求,我们需要在我们的 DispatcherServletregistration 中设置一个 MultipartConfigElement
注意:请阅读下面代码中指定的注释

public class DeploymentDescriptor extends AbstractAnnotationConfigDispatcherServletInitializer {    
     private static final String TMP_FOLDER = "/"; 
        private static final int MAX_UPLOAD_SIZE = 6 * 1024 * 1024; 
    @Override
    protected Class<?>[] getRootConfigClasses() {/*your code*/}
    @Override
    protected Class<?>[] getServletConfigClasses() {/*your code*/}
    @Override
    protected String[] getServletMappings() {/*your code*/}
    /*register the multipartConfigElement in your dispatcher servlet. In the MultipartConfigElement object, we have configured the storage location, maximum individual file size,and the size at which the file upload progress is flushed to the storage location.*/
    @Override
    protected void customizeRegistration(Dynamic registration) {
        super.customizeRegistration(registration);
        registration.setMultipartConfig(
                new MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2L, MAX_UPLOAD_SIZE / 2));
    }
}

第 2 步: 在 Spring 配置文件中定义

StandardServletMultipartResolver
bean :

@Bean
public StandardServletMultipartResolver multipartResolver() 
{
    return new StandardServletMultipartResolver(); 
}

第3步:上传文件:
要上传文件,您可以构建一个简单的表单,其中包含输入类型 file 。 我们需要将表单的编码属性设置为multipart/form-data,方法类型应为POST

<form:form method="POST" action="uploadFile" enctype="multipart/form-data">
         
        <input type="file" name="file" />
        <input type="submit" value="Submit" /> 
</form:form>

第四步:

要在控制器中获取上传的文件,您可以使用

MultipartFile
变量或
StandardServletMultipartResolver
.

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") MultipartFile file, Model model, 
    HttpSession session)
        throws IOException {
    model.addAttribute("file", file);
    // i used the session object for get the context path.<br>it is totally 
    optional you can use your path for store the file . 
    String path = session.getServletContext().getRealPath("/") + 
    file.getOriginalFilename();
    byte arr[] = file.getBytes();
    FileOutputStream stream = new FileOutputStream(path);
    stream.write(arr);
    stream.close();
    return "fileUploadView";
}

第五步:

文件将上传到您想要的位置。就我而言,我的文件上传到此位置 ->

*D: sem\Development\SpringCore.metadata.plugins\org.eclipse.wst.server.core mp0\wtpwebapps\mvcProjects9gFileUpload*

谢谢! 希望对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.