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

时间:2013-05-13 14:46:19

标签: 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);中看不到任何项目。 由于要求,我无法更改请求标头。

1 个答案:

答案 0 :(得分:1)

解决!问题出在spring配置xml文件中。从之前的实施开始

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

所以Spring在我的方法和

之前读取了HttpRequest
upload.parseRequest(request)

读取空流。