1

I am uploading a file. I want to get the file and save to my local system.To do this i am using spring surf webscripts in java. Can any one tell me how i can get my file .

This is my ftl file :

<form name="frmUpload" id="frmUpload"action="${url.context}/upload"     enctype="multipart/form-data" method="get">
<input type="file" size="40" id="toBeUploaded" name="toBeUploaded" tabindex="2" onchange = "document.getElementById('frmUpload').submit()"required />
</form>

I am creating a backed java webscript to get this file. Here is my java code.

public class Upload extends DeclarativeWebScript{

    protected ServiceRegistry serviceRegistry;
    private static final long serialVersionUID = 1L;
    private String fileName;
    private String filePath;

    private File toBeUploaded;  
    private String toBeUploadedFileName = "";  
    private String toBeUploadedContentType;  

    /** Multi-part form data, if provided */
    private FormData formData;

    /** Content read from the inputstream */
    private Content content = null;

    // upload settings
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

      @Override
      protected Map executeImpl(WebScriptRequest req,Status status) {         
          System.out.println("backed webscript called");


          Boolean isMultipart  = false;


          String fileName  = req.getParameter("toBeUploaded");        
          if(fileName == null){
              System.out.println("File Name is null");
          }else{
              System.out.println("File Name is :" + fileName);
          }       


          HttpServletRequest request = ServletUtil.getRequest();
          String file = request.getParameter("toBeUploaded");
          File file2 = new File(file);
          String filePath = request.getSession().getServletContext().getRealPath("/");        
          File fileToCreate = new File(filePath, this.toBeUploadedFileName);          
          System.out.println("filepath "+filePath);

          try {
                FileUtils.copyFile(file2, fileToCreate);
                //validateBundle(fileToCreate);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
               System.out.println("filetocreate "+fileToCreate);


        }

}

file name is comming properly but it is throwing FileNotFoundExeption. Here is stacktrace

java.io.FileNotFoundException: Source 'test.jar' does not exist
        at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:637)
        at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:607)

1 Answers1

1

To get the uploaded form, you need to go via the FormData object. Your code will want to be something like:

    // Get our multipart form
    final ResourceBundle rb = getResources();
    final FormData form = (FormData)req.parseContent();
    if (form == null || !form.getIsMultiPart())
    {
        throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_BAD_FORM);
    }

    // Find the File Upload file, and process the contents
    boolean processed = false;
    for (FormData.FormField field : form.getFields())
    {
        if (field.getIsFile())
        {
            // Logic to process/save the file data here
            processUpload(
                    field.getInputStream(),
                    field.getFilename());
            processed = true;
            break;
        }
    }

    // Object if we didn't get a file
    if (!processed)
    {
        throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_NO_FILE);
    }

If you're sure of the field name of the upload, you can short circuit a few of those bits of logic

Gagravarr
  • 47,320
  • 10
  • 111
  • 156
  • Thanks gagravarr. can you please tell me what is this processUpload method? – Ranveer Singh Rajpurohit Oct 30 '13 at 12:11
  • form.getIsMultiPart() is coming false. I have declared enctype="multipart/form-data" in form.I have configured this webscript as bean in config file. Is bean definition required some more configuration like property etc for multipart form ? – Ranveer Singh Rajpurohit Oct 30 '13 at 12:25
  • `processUpload` is where you put your logic to handle the file! You just need to send your form with the structure, use something like firebird or wireshark to check you're sending the right stuff – Gagravarr Oct 30 '13 at 15:52
  • ok but i am not being able to get my file.I search a lot. some are saying that its a bug in surf webscripts in java. Please can you help me ? – Ranveer Singh Rajpurohit Oct 31 '13 at 04:47
  • Alfresco has at least some examples of doing this, that's where the code in my answer was largely taken from! I can only suggest you try comparing your code and webscript to a working one in Alfresco – Gagravarr Oct 31 '13 at 10:17
  • If i upload an XML file, can i get that into my websctipts and save it to a temp directory so that later i can parse it ? – Ranveer Singh Rajpurohit Nov 06 '13 at 04:38