Struts文件上传到某个目录,无法检索回来?

时间:2012-12-19 04:31:46

标签: struts2

我正在运行Eclipse Java EE和tomcat来运行我的webapp。我使用以下代码将图像文件存储到upload / images / profilepics目录:

public String uploadPhoto() {
    try {
        //get path to upload photo
        String filePath = servletRequest.getSession().
                getServletContext().getRealPath("/uploads/profilepics");

        System.out.println("Server path:" + filePath);

        //creating unique picture name
        Map sess = (Map) ActionContext.getContext().get("session");
        Integer uid = (Integer) sess.get("uid");
        String profilePictureName = uid + "-" + 
                MyUtilityFunctions.createVerificationUrl() + this.userImageFileName;

        //update user record
        //tobe done 
        String imgUrl = filePath + profilePictureName;
        ViewProfileModel pofilePictureUpdate = new ViewProfileModel();
        pofilePictureUpdate.updateUserPhotoUrl(imgUrl, uid);

        //create new File with new path and name
        File fileToCreate = new File(filePath, profilePictureName);

        //copy file to given location and with given name
        FileUtils.copyFile(this.userImage, fileToCreate);
    } catch (Exception e) {
        e.printStackTrace();
        addActionError(e.getMessage());

        return INPUT;
    }
    return SUCCESS;
}

打印filePath后,得到以下结果:

服务器路径:/home/bril/webspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/picvik/uploads/profilepics

现在的问题是,我无法获取图片,或者如果我向<img src="">提供相同的网址,则无法显示任何内容。

请纠正我做错的地方。

1 个答案:

答案 0 :(得分:1)

有建议:

  1. 有很多原因,你不应该以这种方式保存用户图像,就像在另一个问题中提到的@DaveNewton一样。那里 是一些帮助您做出决定的帖子:

    我个人的意见是将它们保存到数据库中,因为你不想要 让你的用户丢失他们的图像。

  2. 如果您需要访问会话,可以查看SessionAware。这应该是访问会话的更好方法。
  3. 您正在使用tomcat作为应用程序容器,您可以将服务器配置为使用其本地安装,这使您可以更轻松地跟踪此情况下的问题。看看Tomcat Server location
  4. 下面的这张照片

    回到你的问题,有不同的方法:

    • 如果您找不到刚刚上传的图片用户,可以查看 手册,见3。
    • 否则,您可以尝试<img src="/uploads/profilepics/<s:property value='profilePictureName'/>"
    • 或者您可以使用流来获取此图片,这是片段:

    JSP:

        <img src="
            <s:url var="profilePic" action="customer-image-action">
                <s:param name="uid" value="%{uid}"/>
            </s:url>
        " alt="kunden logo" />
    

    动作:

    public String execute() throws Exception {
        // filename = somehow(uid);
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        imgPath = request.getSession().getServletContext().getRealPath("/uploads/profilepics/")+filename;
        log.debug("context-path: " + imgPath);
        try {
            inputStream = FileUtils.openInputStream(new File(imgPath));
        } catch (IOException e) {
            log.error(e.getCause(), e);
        }
        return SUCCESS;
    }