无法通过休息从页面上传文件

时间:2017-05-18 12:17:17

标签: spring-boot spring-data-rest

我有Spring Boot我初始化的应用程序

@SpringBootApplication
@ComponentScan(basePackages = { "my.high.level.package" })
@EnableEmailTools
@EnableAsync
public class BookViewApplication {

    public static void main(String[] args) {
        SpringApplication.run(BookViewApplication.class, args);
    }
}

ComponentScan设置为高级包,因此它能够找到所有组件(因为服务,存储库等工作)

我有一个用于显示html

的配置
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/books-home").setViewName("forward:/index.html");
    }
}

index.html显示正常。

我的ServletInitializer看起来像这样

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BookViewApplication.class);
    }

}

我有spring-data-rest资源可以正常使用

@RepositoryRestResource
public interface IBooksRepository extends CrudRepository<Book, Long> {
}

我有controller休息

@RestController("/books-rest")
public class BooksWebController {

    @Autowired
    private IBooksFileRepository fileRepository;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                fileRepository.writeFile(file.getName(), file.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/books-home";
    }

}

我可以访问

localhost:8080/books
localhost:8080/books-home

但是当我尝试使用POST请求

进行访问时
localhost:8080/books-rest

使用此表格

<form method="POST" enctype="multipart/form-data" action="/books-rest/upload">
    <table>
        <tr>
            <td>File to upload:</td>
            <td><input type="file" name="file" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Upload" /></td>
        </tr>
    </table>
</form>

我得到404 not found。有什么问题?

1 个答案:

答案 0 :(得分:0)

请试试这个: 将@RequestParam更改为@RequestBody