我正在尝试从 java 类将文件上传到 Unix 目录并在上传时获取 FileNotFoundException ,但我看不出问题出在哪里。要上传文件,我正在使用 jcraft API 并且此命令“channelSftp.put(new FileInputStream(f), f.getName()); ”上发生错误。文件存在,连接正常并且参数(fileName 和 pathToUpload 正在正确传递。错误是因为没有附加 fileName 目录路径吗?浏览器不会让我发送路径,只是文件名。我会发布我的代码如果有人有明确的解决方案请在此处发布。示例代码将非常有帮助。谢谢大家。
public String uploadFile(String fileName, String pathToUpload) throws IOException {
session = UnixConnect.getInstance();
String SFTPWORKINGDIR = pathToUpload;
String result ="File failed to upload";
String fileName = new File(fileName).getName(); // file is document.pdf
Channel channel = null;
ChannelSftp channelSftp = null;
try {
channel = session.openChannel("sftp");
channel.connect();
//System.out.println("SFTP connection established");
channelSftp = (ChannelSftp)channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
////////////////////////////////////////////
// file not found error in the next line.
//////////////////////////////////////////
channelSftp.put(new FileInputStream(f), f.getName());
//change mode for uploaded file
String fullpath = SFTPWORKINGDIR + fileName;
channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("chmod 770 " + fullpath);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
result = "File " + fileName + " updloaded to directory " + SFTPWORKINGDIR;
}
catch (Exception e) {
System.out.println("Class uploadFile exception: " + e.toString());
}
finally{
if (channel != null) {
channel.disconnect();
}
}
return result;
}
堆栈跟踪:
08:42:02,583 ERROR [STDERR] java.io.FileNotFoundException: test.pdf
(The system cannot find the file specified) 08:42:02,583 ERROR [STDERR] at
java.io.FileInputStream.open(Native Method) 08:42:02,584 ERROR [STDERR] at
java.io.FileInputStream.<init>(FileInputStream.java:120) 08:42:02,584 ERROR [STDERR] at
spt.implement.uploadFile.uploadFile(uploadFile.java:49) 08:42:02,584 ERROR [STDERR] at
spt.controller.UploadController.doPost(UploadController.java:35) 08:42:02,584 ERROR
[STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)