0

我是 Spring 新手,在通过 POST 请求从前端接收 .xls 文件时遇到了一些麻烦。基本上,当我访问“项目/文件”链接时,我收到错误代码 400(错误请求),但前端和后端的参数名称相同。

到目前为止,这是我的代码:

@Controller
public class RestController {

    @Autowired
    private FileService fileService;

    @Consumes("application/vnd.ms-excel")
    @RequestMapping(value = "Project/File",
            method = {RequestMethod.POST, RequestMethod.GET},
            params = {"inputXLS"})
    public @ResponseBody void getCitiriContoriMecanici(
            @RequestParam(value = "inputXLS" , required = true) InputStream inputStream) throws IOException{

        //transform the InputStream to an array of bytes;
        byte[] bytes = IOUtils.toByteArray(inputStream);

        //create a new .xls file
        File file = new File("TEST.xls");  
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        //write a the bytes to a new .xls file
        fileOutputStream.write(bytes);
        fileOutputStream.flush();
        fileOutputStream.close();

        fileService.getFileFromFrontEnd();//this method is used to parse the .xls file
    }

}

谁能给我一个想法如何解决这个问题?

4

1 回答 1

0

看起来您正在尝试使用 Jax-RS@Consumes注释实现文件上传控件。我看到的第一个问题是您正在尝试直接使用application/vnd.ms-excel,但这不是您的文件上传将从您的前端呈现的内容。它期望multipart/form-data为 mime 类型。这样做,您可以@RequestParam("file") MultipartFile file在您的请求映射上使用一个参数来获取文件。

我从未在我的应用程序中使用过 Jax-RS 注释,但您甚至不需要它。您的请求映射可以像这样简单:

@RequestMapping(value ="Project/File", method = RequestMethod.POST)
public void handleFileUpload(@RequestParam("file") MultipartFile file)

如果您想查看更多详细信息https://spring.io/guides/gs/uploading-files/,Spring有一个很好的指南,显示您需要为文件上传做什么

我还应该注意,你已经用 注释了你的映射的返回类型@RequestBody,但是你的返回类型是,所以在这种情况下void不需要。@RequestBody我建议至少有一个返回类型,HttpStatus然后HttpStatus.OK在上传成功时返回。

于 2016-03-16T17:14:46.183 回答