简体   繁体   English

如何使用Spring MVC将图像上传到webapp / resources / images /目录?

[英]How can i upload image to webapp/resources/images/ directory using spring mvc?

i have upload image that is saved in a local fold in c:/temp i want to save it to classpath of project :webapp/resources/images/ my controller class is : 我已经上传了保存在c:/ temp中本地折叠中的图像,我想将其保存到项目的类路径中:webapp / resources / images /我的控制器类是:

@Controller
public class AdminCtrl {

private static String UPLOAD_LOCATION = "C:/temp/";
@Autowired
FileValidator fileValidator;

@InitBinder("fileBucket")
protected void initBinderFileBucket(WebDataBinder binder) {
    binder.setValidator(fileValidator);
}
//--------------------------POST IMAGE -------------------------------------   -----------------------------

 @RequestMapping(value = "/administration/parametres/profile", method = RequestMethod.POST)
public String profilePage(@Valid FileBucket fileBucket,
        BindingResult result, ModelMap model) throws IOException {
    if (result.hasErrors()) {
        System.out.println("validation errors");
        return "redirect:/administration/parametres/profile?error";
    } else {
        System.out.println("Fetching file");
        MultipartFile multipartFile = fileBucket.getFile();
         Now do something with file...
        FileCopyUtils.copy(fileBucket.getFile().getBytes(), new File(UPLOAD_LOCATION + fileBucket.getFile().getOriginalFilename()));
        String fileName = multipartFile.getOriginalFilename();
        model.addAttribute("fileName", fileName);
        return "redirect:/administration/parametres/profile?success";
    }
}

It is not possible to write or save anything to the classpath. 无法将任何内容写入或保存到类路径。 The classpath is just a string with jars and paths, separated by semikolon. classpath只是一个带有jar和路径的字符串,以分号分隔。

Depending on where your app is started, the classpath looks different. 根据应用程序的启动位置,类路径看起来有所不同。 If you run it from a war, there will be only jars in the classpath. 如果您是在战争中运行它,则classpath中将只有罐子。

What you can do, is save the file to a well known location eg from the user.home directory. 您可以做的是将文件保存到一个知名的位置,例如,从user.home目录中。 When you need to read it, you can pick it up from there. 当您需要阅读时,可以从那里拿起它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM