在struts1中上传图像/照片

时间:2014-02-03 10:08:46

标签: image image-uploading struts-1

我想使用Struts1.x和
来编码上传图像(.jpg)/照片到服务器机器 mySQL数据库我有代替文件上传的代码。

请告诉我这里需要进行哪些调整。 TC

文件上传代码:----

公共类FileUploadForm扩展了ActionForm {

private FormFile file;

public FormFile getFile() {
    return file;
}

public void setFile(FormFile file) {
    this.file = file;
}

@Override
public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();

    if( getFile().getFileSize()== 0){
       errors.add("common.file.err",
        new ActionMessage("error.common.file.required"));
       return errors;
    }

    //only allow textfile to upload
    if(!"text/plain".equals(getFile().getContentType())){
        errors.add("common.file.err.ext",
         new ActionMessage("error.common.file.textfile.only"));
        return errors;
    }

        //file size cant larger than 10kb
    System.out.println(getFile().getFileSize());
    if(getFile().getFileSize() > 10240){ //10kb
       errors.add("common.file.err.size",
        new ActionMessage("error.common.file.size.limit", 10240));
       return errors;
    }

    return errors;
}

}

行动类: -

公共类FileUploadAction扩展了Action {

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {

    FileUploadForm fileUploadForm = (FileUploadForm)form;

    FormFile file = fileUploadForm.getFile();

    //Get the servers upload directory real path name
    String filePath = 
           getServlet().getServletContext().getRealPath("/") +"upload";

    //create the upload folder if not exists
    File folder = new File(filePath);
    if(!folder.exists()){
        folder.mkdir();
    }

    String fileName = file.getFileName();

    if(!("").equals(fileName)){  

        System.out.println("Server path:" +filePath);
        File newFile = new File(filePath, fileName);

        if(!newFile.exists()){
          FileOutputStream fos = new FileOutputStream(newFile);
          fos.write(file.getFileData());
          fos.flush();
          fos.close();
        }  

        request.setAttribute("uploadedFilePath",newFile.getAbsoluteFile());
        request.setAttribute("uploadedFileName",newFile.getName());
    }
    return mapping.findForward("success");
}

}

提前致谢!

1 个答案:

答案 0 :(得分:0)

参考struts1.x中图像/照片上传的链接

http://www.roseindia.net/struts/strutsfileuploadandsave.shtml

现在,我正在尝试使用调整此代码在Single go上传多个文件。将保持相同的发布。 Tc& RGDS ACJ