使用jsf 2.2和glassfish进行文件上传4.找不到文件路径错误

时间:2013-10-13 13:11:48

标签: java-ee netbeans jsf-2.2 glassfish-4

这是我得到的错误:

  

java.io.FileNotFoundException:C:\ Users \ Owner \ AppData \ Roaming \ NetBeans \ 7.3.1 \ config \ GF3 \ domain1 \ generated \ jsp \ uploadRamki \ data \ images.jpg(系统无法找到路径指定)

这是我的支持bean:

package beans;

import java.io.IOException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.servlet.http.Part;

@Named(value = "demoBean")
@SessionScoped
public class DemoBean implements Serializable {

    private Part file1;

    public Part getFile1() {
        return file1;
    }

    public void setFile1(Part file1) {
        this.file1 = file1;
    }

    // getters and setters for file1 and file2
    public String upload() throws IOException {
        file1.write("c:/data/" + getFilename(file1));
        return "success";
    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                    .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                    .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

如果你做part.write,它会尝试在glassfish运行的临时目录中写入。

尝试:

        InputStream input = file1.getInputStream();
        FileOutputStream output = new FileOutputStream(URL_FILES + file1.getSubmittedFileName());
        byte[] buf = new byte[1024];
        int len;
        while ((len = input.read(buf)) > 0) {
            output.write(buf, 0, len);
        }
        input.close();
        output.close();