0

我正在尝试从 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)
4

1 回答 1

0

以这种方式工作就可以了:

  1. 在正确的位置创建一个空文件,如下例所示;

    channelSftp.put( new ByteArrayInputStream( "".getBytes() ), 'folder/folder/file.txt');

  2. 使用 FileOutPutStream 写入文件:

    FileOutputStream fos = new FileOutputStream(file);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = is.read(bytes)) >= 0) {
        fos.write(bytes, 0, length);
    }
    
于 2020-07-10T06:38:54.327 回答