开发者

struts 2 File Upload and Save problem

开发者 https://www.devze.com 2023-02-18 08:04 出处:网络
The file is uploaded successfully but it is not getting saved This is the function in my action class public String uploadPhoto()

The file is uploaded successfully but it is not getting saved

This is the function in my action class

public String uploadPhoto()
{
    HttpServletRequest request = ServletActionContext.getRequest();
    String filePath = request.getContextPath();
    File fileToCreate = new File(filePath, this.userImageFileName);

try {
        FileUtils.copyFile(this.userImage, fileToCreate);
        Users user =   userDao.findByUsername((String)session.get("username"));
        user.setPhotoName(filePath+userImageFileName);
        userDao.save(user);
    } catch (IOException e) {
        addActionError(e.getMessage());
        e.pr开发者_如何学GointStackTrace();
        return INPUT;
    }

    return "UPLOADED";
}

I used breakpoints and all statements are executed successfully

But I see no file in my context root


Sumit!!

Struts2 has build in file upload functionality and you can use that one very easily.use that build in interceptor to upload files. Here is the link for the same

File Upload

This interceptor will make available you the file content and now in Action class its your approach how you will save the file using IO system.

Also note that struts2 will put the file in the temp context and it will clean up the context when interceptor will be called in reverse order so make sure to save the uploaded file using IO


I found the solution, I was setting an incorrect path

Instead of

HttpServletRequest request = ServletActionContext.getRequest();
String filePath = request.getContextPath();

it should be

String filePath = ServletActionContext.getServletContext().getRealPath("/");
0

精彩评论

暂无评论...
验证码 换一张
取 消