NoSuchFileException 时尝试在 jave 中上传图像



当我尝试使用 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();
}

以下是 StackTrace:

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)

你创建了一个DiskFileItemFactory,然后,显然,你祈祷它会做点什么。这不是您使用此 API 的方式;必须将factory变量传递给构造函数:new ServletFileUpload(factory)。您的代码段不包含此内容;大概它会比你粘贴的内容更远。

相关内容

  • 没有找到相关文章

最新更新