1

再次,我遇到了检票口问题。我正在尝试使用我的类“FileUploadPanel”上传数据,该类在另一个页面“A 类”上实现:

A级

...
/* uploadfields for Picture and Video */
ArrayList<String> picExt = new ArrayList<String>();
ArrayList<String> videoExt = new ArrayList<String>();
picExt.add("jpg");
videoExt.add("mp4");
final FileUploadPanel picUpload = new FileUploadPanel("picUpload", "C:\\", picExt);
final FileUploadPanel videoUpload = new FileUploadPanel("videoUpload", "C:\\", videoExt);

final Form form = new Form("form"){
      protected void onSubmit() {
      ...
      // Save the path of Video and Picture into Database
      table.setVideo(videoUpload.getFilepath());
      table.setPicture(picUpload.getFilepath());
      ...
}
...

类 FileUploadPanel

public class FileUploadPanel extends Panel {

private static final long serialVersionUID = -2059476447949908649L;
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "C:\\";
private String filepath = "";
private List<String> fileExtensions;

/**
 * Constructor of this Class
 * @param id the wicket-id
 * @param uploadFolder the folder, in which the File will be uploaded 
 * @param fileExtensions List of Strings
 */
public FileUploadPanel(String id, String uploadFolder, List<String> fileExtensions) {
    super(id);
    this.UPLOAD_FOLDER = uploadFolder;
    this.fileExtensions = fileExtensions;
    add(fileUpload = new FileUploadField("fileUpload"));
}

@Override
public void onComponentTag(ComponentTag tag){
    // If no file is selected on startup
    if(fileUpload.getFileUpload() == null){
        return;
    }
    final FileUpload uploadedFile = fileUpload.getFileUpload();
    if (uploadedFile != null) {

        // write to a new file, 
        File newFile = new File(UPLOAD_FOLDER
            + uploadedFile.getClientFileName());
        filepath = UPLOAD_FOLDER + uploadedFile.getClientFileName();

        // if file in upload-folder already exists -> delete it
        if (newFile.exists()) {
            newFile.delete();
        }

        try {
            newFile.createNewFile();
            uploadedFile.writeTo(newFile);

            info("saved file: " + uploadedFile.getClientFileName());
        } catch (Exception e) {
            throw new IllegalStateException("Error");
        }
     }
}

public String getFilepath() {
    return filepath;
}

}

好吧,如果我在“A 类”上使用提交按钮,图片和视频会保存在 C:\ 上,这到目前为止非常好。我以为我终于和检票口相处了,但我欢呼得太快了……

问题:数据库中没有保存正确的路径,以“A类”的形式处理我真的不明白,因为我的FileUploadPanel的onComponentTag(...)必须在使用提交按钮时执行。那是因为我在 onComponentTag(...) 中添加了一些验证,例如“图片必须是 JPG 或不会被保存” - 这很有效。所以我确定,使用表单的提交按钮时会执行 onComponentTag(...) ,这也意味着文件路径应该是最新的。

这次我做错了什么?

预先感谢!

问候 V1nc3nt

4

1 回答 1

0

您正在使用

文件 newFile = new File(UPLOAD_FOLDER + uploadFile.getClientFileName());

此代码创建一个新文件。

而不是它,你可以试试这个:

文件文件 = 新文件(UPLOAD_FOLDER,uploadFile.getClientFileName());

然后获取绝对路径保存

newFile.getAbsolutePath();

于 2012-12-31T06:49:15.047 回答