嵌入了Jersey文件上传的Java tomcat

时间:2015-11-30 12:37:26

标签: java tomcat file-upload jersey

我正在使用tomcat嵌入式和jersey REST构建一个java应用程序。

我需要做的是在这个应用程序中实现一个非常简单(和单个)的文件上传,但是我无法在任何地方找到我的上下文的指南......我刚刚找到了一个文件上传解决方案,但不是嵌入式tomcat。

有什么建议吗?

感谢大家的建议并抱歉我的英文

1 个答案:

答案 0 :(得分:0)

如果您使用Spring Boot for Tomcat嵌入式,那么下面的代码示例将帮助您..

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @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)));
                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.";
        }
    }

}

参考。的     https://spring.io/guides/gs/uploading-files/