使用Spring,commons-file upload上传图片

时间:2015-04-19 02:05:51

标签: java spring spring-mvc file-upload

我试图在thisthis教程之后上传图片但不使用maven。

以下是与上传有关的配置:

的applicationContext.xml

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

我的表格:

<form:form 
        action="${ contextPath }admin/add-product" 
        method="POST" modelAttribute="addInventoryItemDto"
        enctype="multipart/form-data">
        <table>
        ....
        <tr>
            <td><b>Image:</b></td>
            <td><input type="file" name="image" /></td>
        </tr>
        ....

控制器

@RequestMapping( value = "/add-product", method = RequestMethod.POST )
    public String addProduct( 
    @ModelAttribute( "addInventoryItemDto" ) @Valid AddInventoryItemDto inventoryDto,
    @RequestParam( "image" ) MultipartFile img ) {
        System.out.println("ContentType:" + img.getContentType());
        return "admin/add-product";
    }

我收到404 Bad Request但是当我删除Controllerform中与文件相关的内容时,请求已正确发送到我的控制器

我错过了什么或做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试添加此标记:

  <spring:url value="/add-product?${_csrf.parameterName}=${_csrf.token}" var="addItem"/>

并将其添加到action属性:

<form:form 
    action= "${addItem}" 
    method="POST" modelAttribute="addInventoryItemDto"
    enctype="multipart/form-data" >
    <table>
    ....
    <tr>
        <td><b>Image:</b></td>
        <td><input type="file" name="image" /></td>
    </tr>
    ....

如果这不起作用,请尝试将MultiPartHttpServletRequest对象添加到控制器:

@RequestMapping( value = "/add-product", method = RequestMethod.POST )
public String addProduct( 
@ModelAttribute( "addInventoryItemDto" ) @Valid AddInventoryItemDto inventoryDto,
MultiPartHttpServletRequest request,
@RequestParam( "image" ) MultipartFile img ) {
    System.out.println("ContentType:" + img.getContentType());
    return "admin/add-product";
}

答案 1 :(得分:0)

我刚刚移动了multipartResolver

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

到我的servlet-dispatcher配置。看起来multipartResolver是spring MVC的一部分而不是spring core