Spring MVC将上传的MultipartFile保存到特定文件夹

Ale*_*der 31 spring tomcat file image-uploading

我想将上传的图像保存到Tomcat上部署的Spring 3 MVC应用程序中的特定文件夹中

我的问题是我无法将上传的图像文件保存到运行applciation的主机.

这是我尝试过的:

private void saveFile(MultipartFile multipartFile, int id) throws Exception {
    String destination = "/images/" + id + "/"  + multipartFile.getOriginalFilename();
    File file = new File(destination);
    multipartFile.transferTo(file);
}
Run Code Online (Sandbox Code Playgroud)

结果:FileNotFoundException - 是的,我确实想要创建这个文件!?!

我尝试使用context.getRealPathgetResources("destination"),但没有任何成功.

如何使用我的多部分文件的内容在我的应用程序的特定文件夹中创建新文件?

小智 31

这段代码肯定会对你有所帮助.

String filePath = request.getServletContext().getRealPath("/"); 
multipartFile.transferTo(new File(filePath));
Run Code Online (Sandbox Code Playgroud)

  • 我收到“没有这样的文件或目录”错误。 (2认同)

Yul*_*mok 14

让我们在webapp中创建uploads目录并在webapp/uploads中保存文件:

@RestController
public class GreetingController {

    private final static Logger log = LoggerFactory.getLogger(GreetingController.class);

    @Autowired
    private HttpServletRequest request;


    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
        public
        @ResponseBody
        ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
            if (!file.isEmpty()) {
                try {
                    String uploadsDir = "/uploads/";
                    String realPathtoUploads =  request.getServletContext().getRealPath(uploadsDir);
                    if(! new File(realPathtoUploads).exists())
                    {
                        new File(realPathtoUploads).mkdir();
                    }

                    log.info("realPathtoUploads = {}", realPathtoUploads);


                    String orgName = file.getOriginalFilename();
                    String filePath = realPathtoUploads + orgName;
                    File dest = new File(filePath);
                    file.transferTo(dest);
Run Code Online (Sandbox Code Playgroud)

代码
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);

如果我从Idea IDE运行应用程序,则返回下一个路径
C:\Users\Iuliia\IdeaProjects\ENumbersBackend\src\main\webapp\uploads\

如果我使.war并在Tomcat下运行它,那么下一条路径:
D:\Programs_Files\apache-tomcat-8.0.27\webapps\enumbservice-0.2.0\uploads\

我的项目结构:
在此输入图像描述


Die*_*sus 7

您可以从 multipartfile 获取 inputStream 并将其复制到您想要的任何目录。

public String write(MultipartFile file, String fileType) throws IOException {
    String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss-"));
    String fileName = date + file.getOriginalFilename();
    
    // folderPath here is /sismed/temp/exames
    String folderPath = SismedConstants.TEMP_DIR + fileType;
    String filePath = folderPath + File.separator + fileName;
    
    // Copies Spring's multipartfile inputStream to /sismed/temp/exames (absolute path)
    Files.copy(file.getInputStream(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
    return filePath;
}
Run Code Online (Sandbox Code Playgroud)

这适用于 Linux 和 Windows。

  • 好例子。只是用 File.separator 替换了“/” (2认同)