简体   繁体   中英

Geting HTTP Status 400 - Required MultipartFile parameter 'file' is not present in spring

I am trying to upload a file using spring . Below is my code how I am working on it but if I try to use it I am getting this response :

HTTP Status 400 - Required MultipartFile parameter 'file' is not present

I dont get what the error is.

I am using advanced rest client for testing and I am uploading file as an attachment.

My Javacode:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file)
    {
        String name= "test.xlsx";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

Spring needs the

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

bean to handle file-uploads.

You should register this bean in your application context file.

The Content-Type should also be valid. In your case enctype="multipart/form-data"

EDIT1:

You can give the upload and memory size to the bean properties:

  <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- max upload size in bytes -->
        <property name="maxUploadSize" value="20971520" /> <!-- 20MB -->

        <!-- max size of file in memory (in bytes) -->
        <property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->

    </bean>

when you select the file in advance rest client, on the right side there is a input box , write in that input box name of the parameter , in your case name of parameter is file

Parameter name defined here in controller @RequestParam("file")

在此输入图像描述

当我在Krajee bootstrap inputfile示例中已经很好地配置了bean id之后,我在参数“file”的输入框名称中写入后,它对我有用(“ https://github.com/kartik-v/bootstrap-fileinput “)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM