coolmego February 2016

How to upload a file(txt,pdf) and show it in the same webpage?

I am writing a logic where the user uploads a text file when user visits the webpage for the first time(eg. in his profile page). The next time when the user visits the webpage he should be able to find the uploaded file as a link.

So far i have been able to upload the file in a user specific path and dwelling on how to show it in the webpage.

I am following mkyong but the problem i find here is the action result is in stream whereas in my case the valuestack has other action details.

Code Fragment :

1.Action Class

public String uploadResume(){

    try{

        if(uploadFile==null){
            throw new NullPointerException();
        }

    File file = new File("/Users/shibasish/Documents/","/" 
                    + GenerateTimestampID.generateTimestamp()+"/shibasish");
    if (!file.exists()) {
        if (file.mkdirs()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }
    String filePath = file.getPath();
    File fileToCreate = new File(filePath, uploadFileFileName);
    FileUtils.copyFile(uploadFile, fileToCreate);       

    }catch(NullPointerException e){
        addActionError("Please upload a resume");
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return "success";
}

2.struts.xml

<action name="uploadResume" class="com.msventure.web.actions.CompleteProfileAction" 
              method="uploadResume"> 
    <interceptor-ref name="defaultStack">
    <param name="fileUpload.allowedTypes">
        text/plain,application/pdf,application/octet-stream
    </param>
</interceptor-ref> 
        <result name="success">/profile.jsp</result&g        

Answers


Andrea Ligios February 2016

You can't return both a JSP page and a binary file.

When returning a JSP, use a dispatcher result, when returning a file, use a stream result.

After you've uploaded the file, you have two choices:

1. Show only the file

post the form in a new tab with target="_blank" and return a stream result; the user will end up having two tabs, one with the profile, the other with the document.

2. Show a JSP with the file embedded in it

Use an <iframe> in the profile page, and post the form targeting the iframe, with target="name_of_the_frame_here".

There are more complex ways (returning a JSP, and composing serverside an id that you'll use on a secondary action called by the iframe to fetch the document), but I'd just go with solution #2.


coolmego February 2016

Although Andrea have provided the best possible approach, i am uploading the code that i used using iframe and downloading user specific files on relogin. I hope this helps.

1.JSP : This is the JSP inside iframe

<s:form id="login" name="login" method="post" action="uploadResume" 
                                             enctype="multipart/form-data">
    <s:file name="uploadFile" label="Select a File to upload" size="40"/>
    <s:submit value="submit" name="submit"/>
</s:form><a href="downloadResume">Download file</a>

2.Action method : After uploading the resume, persist the user specific path.I have used cookies for user identification.

public String downloadResume() {

    try {

        Cookie[] currentCookie;
        String usrCookie = "sample";
        String cookieFlg;
        currentCookie = request.getCookies();

        for (int i = 0; i < currentCookie.length; i++) {
            if (currentCookie[i].getName().equals("_usr")) {
                usrCookie = currentCookie[i].getValue();
            }
        }

        if (!usrCookie.equalsIgnoreCase("sample")) {

            userProfileObj = new UserProfile();

            String pathloc=userProfileObj.getResumePath(usrCookie);

            if(pathloc==null){
                //throw new NullPointerException();
                addActionError("Please upload a resume");
                return "fail";
            }
            else{
            File folder = new File(pathloc);
            File[] listFile=folder.listFiles();
            File fileToDownload=new File(pathloc+"/"+listFile[1].getName());
            for(int i=0;i<listFile.length;i++){
                System.out.println("list of files : "+listFile[i].getName());
            }
            //System.out.print("Files in the directory : "+fileToDownload);

            inputStream = 

Post Status

Asked in February 2016
Viewed 1,408 times
Voted 9
Answered 2 times

Search




Leave an answer