java - 在 Java 中使用 multipart/form-data 获取 HTTP POST 请求中的数据(Spring)

标签 java spring servlets file-upload httprequest

我想从 flash 上传文件,我的原始请求(使用 Fiddler 缓存):

    POST /api/v1/exercises/uploadTableImage HTTP/1.1
    x-flash-version: 11,2,202,228
    Content-Type: multipart/form-data; boundary=jdmlcuucuseqxyyyvsfjbfixukdbuesq
    Cache-Control: no-cache
    Content-Length: 93737
    User-Agent: Shockwave Flash
    Host: localhost:8080
    Pragma: no-cache
    Cookie: JSESSIONID=BA009CDDBD828B931FCC3B0894FD7DCD;

    --jdmlcuucuseqxyyyvsfjbfixukdbuesq
    Content-Disposition: form-data; name="Filename"

    20er_1_1.jpg.jpg
    --jdmlcuucuseqxyyyvsfjbfixukdbuesq
    Content-Disposition: form-data; name="filedata"; filename="20er_1_1.jpg.jpg"
    Content-Type: application/octet-stream

    1


    --jdmlcuucuseqxyyyvsfjbfixukdbuesq
    Content-Disposition: form-data; name="Upload"

    Submit Query
    --jdmlcuucuseqxyyyvsfjbfixukdbuesq--

我想保存发布的文件

@Controller
@RequestMapping(API_ROOT+"exercises")
public class ImageUploadingController {

    private final String imagesWebPath = "uploaded";

    @RequestMapping(value = "uploadTableImage", method = POST)
    public void uploadImage(HttpServletRequest request) throws Exception {

        FileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        FileItem uploadedFile = null;
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if ("Filedata".equals(item.getFieldName())) {
                uploadedFile = item;
                break;
            }
        }

        if (uploadedFile != null) {
            File file = new File(request.getRealPath(imagesWebPath)+File.separator+uploadedFile.getName());
            file.getParentFile().mkdirs();
            file.createNewFile();
            uploadedFile.write(file);

        } else {
            throw new RuntimeException("No files found");
        }
    }

但运气不好,我在 List items = upload.parseRequest(request); 中没有看到任何项目。 由于要求,我无法更改请求 header 。

最佳答案

解决了!问题出在 spring 配置 xml 文件中。从之前的实现左边

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="100000"/>
</bean>

So spring read HttpRequest before my method and

upload.parseRequest(request)

读取空流。

关于java - 在 Java 中使用 multipart/form-data 获取 HTTP POST 请求中的数据(Spring),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16524887/

相关文章:

java - 当我运行我的应用程序时,我的图片没有出现在我的手机上

java - 如何使用注释设置消息驱动 bean 的主体?

java - Selenium 的范围报告中出现错误

java - 如何使用 mongodb 和 NumberLong 计算平均值

java - 使用Servlet-JSP登录

java - 如何使用 Eclipse 为 Jetty 编写一个简单的 Servlet?

spring - Spring中的错误NoSuchFieldException是什么意思?

Spring security login-processing-url 抛出 405 请求方法 POST 不支持

java - HTTP Get - Python 与 Spring Rest 模板

java - Tomcat 上的虚拟主机