使用formData发送多部分文件时发生错误

时间:2019-11-19 05:54:09

标签: reactjs spring-boot multipart

我想使用“ formData”发送文件。
我将Spring Boot用于后端,并将React.js用于前端。
使用PostMan,我检查了Spring引导程序以确保正确存储了文件。
但是,当我将文件附加到formData并将其发送时,会发生错误。

以下是错误。

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]



以下是React.js的一部分

class Test extends Component {
    constructor(props){
        super(props);
    this.state = {
        fileList:[]
    };
    this.uploadNewWebtoon = this.uploadNewWebtoon.bind(this);
            this.onChange = this.onChange.bind(this);
}

onChange=({ fileList })=> {
    this.setState({ fileList }, function(){
        console.log(this.state.fileList[0].originFileObj)
     })
 }

 uploadNewWebtoon() {
    try {
        uploadFile(this.state.fileList[0].originFileObj)


    } catch(error) {
            notification.error({
                message: 'Cheeze Toon',
                description: error.message || 'Try again.'
            });
        }
    }
    render() {
        return (
            <div className="newAdd-container">
                <Form onSubmit={this.uploadNewWebtoon}>
                <Form.Item label="Thumbnail">
                        <Dragger onChange={this.onChange} beforeUpload={() => false} >
                            <p className="ant-upload-drag-icon">
                            <Icon type="inbox" />
                            </p>
                            <p className="ant-upload-text">Click or drag file to this area to upload</p>
                            <p className="ant-upload-hint">
                            Support for a single or bulk upload. Strictly prohibit from uploading company data or other
                            band files
                            </p>
                        </Dragger>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" className="newAddButton" size="large" htmlType="submit">Save</Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }
}

我正在使用称为Ant Design的React UI库。因此,我遵循了官方文档,并以与this.state.fileList[0].originFileObj相同的意义使用了event.target.files[0]


filesList [0]的orginFileObj由以下内容组成
enter image description here



下面是我创建formData,将文件附加到append()并将其传输到fetch的部分。

import { API_BASE_URL, ACCESS_TOKEN} from '../constants';



const request = (options) => {
    const headers = new Headers()

    if(localStorage.getItem(ACCESS_TOKEN)) {
        headers.append('Authorization', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))
    }

    const defaults = {headers: headers};
    options = Object.assign({}, defaults, options);

    return fetch(options.url, options)
    .then(response => 
        response.json().then(json => {
            if(!response.ok) {
                return Promise.reject(json);
            }
            return json;
        })
    );
};


export function uploadFile(fileList) {
        const formData = new FormData();
        formData.append('fileList', fileList);
        return request({
            url:API_BASE_URL + "/newToonSave",
            method: 'POST',
            body : formData
        })
}

由于登录功能,JWT TOKEN包含在标题中。

我试图在附加值后附加选项(例如fileName = fileList.name ...)
但是结果是一样的。



这是spring boot控制器的一部分。

@RestController
@RequestMapping("/api")
public class ToonController {

    private static final Logger logger = LoggerFactory.getLogger(ToonController.class);

    @Autowired
    private ToonStorageService toonStorageService;

    @PostMapping(value = "/newToonSave", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    @PreAuthorize("hasRole('ADMIN')")
    public ToonStorage uploadFile(@RequestParam("file") MultipartFile file) {

        ToonStorage toonStorage = toonStorageService.storeFile(file);

        return toonStorage;

    }

}


我不知道为什么它不起作用...

我认为Spring Boot需要一个与文件上传相关的库。

因此我将Dependency添加到pom.xml,并将@Bean添加到Application.java。

但是,发生相同的错误。

<dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
@SpringBootApplication
//auto convert
@EntityScan(basePackageClasses = {DemoApplication.class, Jsr310JpaConverters.class})
@EnableConfigurationProperties({
    FileStorageProperties.class
})
public class DemoApplication {

    @PostConstruct
    void init(){
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    return factory.createMultipartConfig();
    }

    @Bean
    public MultipartResolver multipartResolver() {
    org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(512000000);
    return multipartResolver;
    }

}





我已经挣扎了四天。非常感谢您的帮助。

0 个答案:

没有答案