Tum
Tum

Reputation: 3652

Gwt SampleUploadServlet, How to save a file into a folder in server (JAVA, GWT)?

I copied this code (allow user to upload image from client to server) from internet https://code.google.com/p/gwtupload/source/browse/samples/src/main/java/gwtuploadsample/server/SampleUploadServlet.java?r=e0b4acbaa632114978b085801a004116b6dbcf52

But it doesn't give an actual code to save the file into a folder in server

package my.server;
public class SampleUploadServlet extends UploadAction{


private static final long serialVersionUID = 1L;

  Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>();
  /**
   * Maintain a list with received files and their content types. 
   */
  Hashtable<String, File> receivedFiles = new Hashtable<String, File>();

  /**
   * Override executeAction to save the received files in a custom place
   * and delete this items from session.  
   */
  @Override
  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
    String response = "";
    int cont = 0;
    for (FileItem item : sessionFiles) {
      if (false == item.isFormField()) {
        cont ++;
        try {
          /// Create a new file based on the remote file name in the client
          // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_");
          // File file =new File("/tmp/" + saveName);

          /// Create a temporary file placed in /tmp (only works in unix)
          // File file = File.createTempFile("upload-", ".bin", new File("/tmp"));

          /// Create a temporary file placed in the default system temp folder
          File file = File.createTempFile("upload-", ".bin");
          item.write(file);

          /// Save a list with the received files
          receivedFiles.put(item.getFieldName(), file);
          receivedContentTypes.put(item.getFieldName(), item.getContentType());

          //Window.alert(file.getAbsolutePath()+" oook");
          //String s=file.getAbsolutePath()+" oook";
          /// Send a customized message to the client.
          response += "File saved as " + file.getAbsolutePath();
          //FileWriter fstream = new FileWriter(file.getAbsolutePath()+"//folder//out.txt",true);
          //SEEM WE NEED TO DO SOMETHING HERE TO SAVE A FILE INTO THE FOLDER.
        } catch (Exception e) {
          throw new UploadActionException(e);
        }
      }
    }

   // System.out.println(response);
    /// Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    /// Send your customized message to the client.
    return response;
  }

  /**
   * Get the content of an uploaded file.
   */
  @Override
  public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String fieldName = request.getParameter(UConsts.PARAM_SHOW);
    File f = receivedFiles.get(fieldName);
    if (f != null) {
      response.setContentType(receivedContentTypes.get(fieldName));
      FileInputStream is = new FileInputStream(f);
      copyFromInputStreamToOutputStream(is, response.getOutputStream());
    } else {
      renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
   }
  }

  /**
   * Remove a file when the user sends a delete request.
   */
  @Override
  public void removeItem(HttpServletRequest request, String fieldName)  throws UploadActionException {
    File file = receivedFiles.get(fieldName);
    receivedFiles.remove(fieldName);
    receivedContentTypes.remove(fieldName);
    if (file != null) {
      file.delete();
    }
  }
}

So suppose I have a folder image in Package "server", then How can I save the file into server/image?

I think you can do this with only Java knowlege, you don't need Gwt knowledge.

Upvotes: 0

Views: 1473

Answers (1)

Ashish
Ashish

Reputation: 14707

This is not my solution. Someone has already answered it here

You should use File#createTempFile() which takes a directory instead.

File file = File.createTempFile("upload-", ".bin", new File("/path/to/your/uploads"));
item.write(file);

Or if you actually want to move the temp file to another location afterwards, use File#renameTo().

File destination = new File("/path/to/your/uploads", file.getName());
file.renameTo(destination);

Upvotes: 1

Related Questions