Подтвердить что ты не робот

Spring MVC сохраняет загруженную MultipartFile в определенную папку

Я хочу сохранить загруженные изображения в определенную папку в приложении Spring 3 MVC, развернутом на Tomcat

Моя проблема заключается в том, что я не могу сохранить загруженные файлы изображений на хост, на котором выполняется приложение.

Вот что я пробовал:

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

Результат: FileNotFoundException - Да, конечно, я хочу создать этот файл!?!

Я попробовал его с помощью context.getRealPath или getResources("destination"), но без каких-либо успехов.

Как создать новый файл в определенной папке моего приложения с содержимым моего многостраничного файла?

4b9b3361

Ответ 1

Этот код поможет вам.

String filePath = request.getServletContext().getRealPath("/"); 
multipartFile.transferTo(new File(filePath));

Ответ 2

Создайте каталог uploads в webapp и сохраните файлы в 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);

код
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\

Моя структура проекта:
введите описание изображения здесь

Ответ 3

Я видел пример spring 3 с использованием конфигурации xml (обратите внимание, что это не wok для spring 4.2. *): http://www.devmanuals.com/tutorials/java/spring/spring3/mvc/spring3-mvc-upload-file.html `

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
<property name="uploadTempDir" ref="uploadDirResource" />
</bean>

<bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
<constructor-arg>
<value>C:/test111</value>
</constructor-arg>
</bean>

Ответ 4

String ApplicationPath = 
        ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("");

Вот как получить реальный путь приложения в Spring (без использования ответа, сеанса...)

Ответ 5

На Ubuntu у меня работает следующее:

String filePath = request.getServletContext().getRealPath("/");
File f1 = new File(filePath+"/"+multipartFile.getOriginalFilename());
multipartFile.transferTo(f1);

Ответ 6

Вы можете получить inputSream из multipartfile и скопировать его в любой каталог.

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 + "/" + fileName;

    // Copies Spring multipartfile inputStream to /sismed/temp/exames (absolute path)
    Files.copy(file.getInputStream(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
    return filePath;
}

Это работает как для Linux, так и для Windows.