8
respostas

erro de caminho ou arquivo não encontrado

HTTP Status 500 – Internal Server Error Type Exception Report Message Request processing failed; nested exception is java.lang.RuntimeException: java.io.IOException: java.io.FileNotFoundException: C:\apache-tomcat-7.0.94\work\Catalina\localhost\dinamico\arquivos-sumario\C:\Users\andre.silva\Desktop\1.txt (A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta)

8 respostas
package infra;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileSaver {

    @Autowired
    private HttpServletRequest request;

    public String write(String baseFolder, MultipartFile file) {
        try {
            // String realPath =
            // request.getServletContext().getRealPath("/"+baseFolder);
            // String path = realPath + "/" + file.getOriginalFilename();
            // file.transferTo(new File(path));
            // return baseFolder + "/" + file.getOriginalFilename();

            String path = baseFolder + "/" + file.getOriginalFilename();
            file.transferTo(new File(path));
            return path;
        } catch (IllegalStateException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
import infra.FileSaver;

import java.util.List;

import javax.validation.Valid;

import modelos.Produto;
import modelos.TipoPreco;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import validation.ProdutoValidation;
import dao.ProdutoDao;

@Controller
@RequestMapping("/produtos")
public class ProdutosController {
    @Autowired
    private FileSaver fileSaver;
    @Autowired
    private ProdutoDao produtoDao;

    @RequestMapping("/form")
    public ModelAndView form(Produto produto) {
        ModelAndView mv = new ModelAndView("/produtos/form");
        mv.addObject("tipo", TipoPreco.values());
        return mv;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView gravar(MultipartFile sumario, @Valid Produto produto,
            BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return form(produto);
        }
        String path = fileSaver.write("arquivos-sumario", sumario);
        produto.setSumarioPath(path);
        produtoDao.gravar(produto);
        redirectAttributes.addFlashAttribute("sucesso",
                "Produto cadastrado com sucesso!");
        return new ModelAndView("redirect:produtos");
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView listar() {
        List<Produto> produtos = produtoDao.listar();
        ModelAndView mv = new ModelAndView("/produtos/lista");
        mv.addObject("produtos", produtos);
        return mv;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(new ProdutoValidation());
    }
}
import infra.FileSaver;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import controlers.HomeController;
import dao.ProdutoDao;

@EnableWebMvc
@ComponentScan(basePackageClasses = { HomeController.class, ProdutoDao.class,
        FileSaver.class})
public class AppWebConfiguration {
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages");
        messageSource.setDefaultEncoding("utf-8");
        messageSource.setCacheSeconds(1);
        return messageSource;
    }

    @Bean
    public FormattingConversionService mvcConversionService() {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
        DateFormatterRegistrar formatterRegistrar = new DateFormatterRegistrar();
        formatterRegistrar.setFormatter(new DateFormatter("dd/MM/yyyy"));
        formatterRegistrar.registerFormatters(conversionService);
        return conversionService;
    }

    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }
}

Olá andrré!

Estou analisando seu código, já lhe dou um retorno!

Reparei que você comentou um trecho do código que em teoria estaria correto:

   // String realPath =
   // request.getServletContext().getRealPath("/"+baseFolder);
  // String path = realPath + "/" + file.getOriginalFilename();
 // file.transferTo(new File(path));
// return baseFolder + "/" + file.getOriginalFilename();

Se você usar esse trecho ele ainda não funciona? Tenta testar assim:

@Component
public class FileSaver {

    @Autowired
    private HttpServletRequest request;

    public String write(String baseFolder, MultipartFile file) {
        try {
            String realPath = request.getServletContext().getRealPath("/"+baseFolder);
            String path = realPath + "/" + file.getOriginalFilename();
            file.transferTo(new File(path));
            return baseFolder + "/" + file.getOriginalFilename();
        } catch (IllegalStateException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Aguardo seu retorno!

Olá andrré!

Conseguiu resolver?

bom dia ainda não está 

dando o seguinte erro quando cadastro e insiro um arquivo.

Type Exception Report Message Request processing failed; nested exception is java.lang.RuntimeException: java.io.IOException: java.io.FileNotFoundException: C:\apache-tomcat-7.0.94\wtpwebapps\dinamico\arquivos-sumario\C:\Users\andre.silva\Desktop\1.txt (A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta) Description The server encountered an unexpected condition that prevented it from fulfilling the request. Exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException: java.io.IOException: java.io.FileNotFoundException: C:\apache-tomcat-7.0.94\wtpwebapps\dinamico\arquivos-sumario\C:\Users\andre.silva\Desktop\1.txt (A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)

Olá andrré!

Sua construção de path está estranha, veja:

C:\apache-tomcat-7.0.94\wtpwebapps\dinamico\arquivos-sumario\C:\Users\andre.silva\Desktop\1.txt

Observe que por algum motivo ele está chamando o diretório C:\ duas vezes;

Uma solução temporária seria você tentar remover essa parte da url deixando somente o começo:

C:\apache-tomcat-7.0.94\wtpwebapps\dinamico\arquivos-sumario\

Você poderia tentar fazer isso usando o método replace da classe String:

String pathErrado = "C:\\apache-tomcat-7.0.94\\wtpwebapps\\dinamico\\arquivos-sumario\\C:\\Users\\andre.silva\\Desktop\\1.txt";
String  pathCerto = pathErrado.replace("C:\\Users\\andre.silva\\Desktop\\1.txt", "");

Dessa forma, talvez, dê certo.

Uma coisa também que pode estar dando erro é devido a forma que o Windows lida com diretórios. Usamos barras invertidas nesse Sistema Operacional: \

Já no Linux ou MacOS usamos a barra normal: /

Por isso quando você faz isso:

  String path = baseFolder + "/" + file.getOriginalFilename();

E isso:

 String realPath = request.getServletContext().getRealPath("/"+baseFolder);
 String path = realPath + "/" + file.getOriginalFilename();
 file.transferTo(new File(path));
 return baseFolder + "/" + file.getOriginalFilename();

Ele pode estar se confundindo na hora de fazer a criação do path já que você está passando uma barra que não é usada no Windows.

Uma outra tentativa de resolver seria tentar inverter as barras para que fiquem compatíveis com o sistema que você está utilizando.

Espero que dê certo!

Bons estudos.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software