Spring boot上传文件路径

时间:2014-05-03 16:20:22

标签: spring-mvc spring-boot

我尝试使用 Spring Boot 上传一些文件。 还有一个问题,我应该在哪里指出我的文件存储的路径。 您可以在下面看到我的UploadController,模板和Application类。

@Controller
public class FileUploadController {

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

}

这是我的表格。

<div class="container">
            <form method="POST" enctype="multipart/form-data"
                  action="/upload">
                File to upload:
                <input type="file" name="file"/><br/> Name:
                <input
                    type="text" name="name"/><br/> <br/> <input type="submit"
                                                               value="Upload"/> Press here to upload the file!
            </form>
        </div>

这是Application类。

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

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

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultiPartConfigFactory factory = new MultiPartConfigFactory();
        factory.setMaxFileSize("128KB");
        factory.setMaxRequestSize("128KB");
        return factory.createMultipartConfig();
    }

}

3 个答案:

答案 0 :(得分:1)

我认为这个问题没有“正确”的答案。把文件放在任何你喜欢的地方,如果它适合你,就放在哪里。这完全取决于实际的商业目的。

答案 1 :(得分:1)

以下代码行包含您添加文件的位置。

new File(name + "-uploaded")

由于您没有指定完整路径,因此从启动应用程序时将保存在java类路径中。

对于生产系统,您应该在特定的共享存储中指定它,其中文件经常被备份,并且存储的大小适合您要上载的文件类型。

如果你在这里使用Windows就是一个例子:

new File("d:/yourApplicationName/" + name + "-uploaded")

如果你使用linux,这里有一个例子:

new File("/home/yourApplicationName/" + name + "-uploaded")

注意:您应首先创建目录“yourApplicationName”,否则您将获得例外。

答案 2 :(得分:0)

当然,您需要为多部分请求注册解析器。此外,您还需要为此示例工作添加apache常见上载的依赖项。与Sping Boot的RC4变化相关的问题

它似乎是

@Configuration
public class Application{
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }
}