当我尝试使用 post 方法通过表单上传文件NoSuchFileException
时,会发生类型错误,我不知道为什么。
这是代码:
if (req.getPart("file") != null) {
Part file = req.getPart("file");
String fileName = file.getSubmittedFileName();
DiskFileItemFactory factory = new DiskFileItemFactory();
File repository = new File("./uploads");
factory.setRepository(repository);
try {
File thisFile = new File(repository, fileName);
try (InputStream input = file.getInputStream()) {
Files.copy(input, thisFile.toPath());
}
} catch (IOException e) {
e.printStackTrace();
}
UserDao.getInstance().addPicture("./uploads" + fileName, oldUser);
UserDao.getInstance().update(user, oldUser);
}
我确定出了点问题,但我看不到它...有人可以帮我吗?
一开始我有这个代码,但试图解决错误我改变了它:
Part file = req.getPart("file");
String filename = file.getSubmittedFileName();
DiskFileItemFactory factory = new DiskFileItemFactory();
File repository = new File("./uploads");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(req);
File thisFile = new File(repository, filename);
try (InputStream input = file.getInputStream()) {
Files.copy(input, thisFile.toPath());
}
} catch (FileUploadException e) {
e.printStackTrace();
}
这是堆栈跟踪:
java.nio.file.NoSuchFileException: ./uploads/photo.jpeg
java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:219)
java.base/java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:478)
java.base/java.nio.file.Files.newOutputStream(Files.java:223)
java.base/java.nio.file.Files.copy(Files.java:3143)
com.marcosvalens.controller.UserFormController.doPost(UserFormController.java:82)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
com.marcosvalens.interceptor.RequestLoginFilter.doFilter(RequestLoginFilter.java:39)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)