Java Jersey - How can i write a file in my Tomcat

2019-08-04 13:58发布

问题:

I got a problem in writing the file to the localhost of the tomcat server in my system.

How can i write file in the location mentioned Below ?? I am getting a response as the file uploaded in the location mentioned. But i don't know where it is stored in my system.. Is it the right way of doing ??

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail) {

    String uploadedFileLocation = "http://127.0.0.1:8080/Attachments"
            + fileDetail.getFileName();

    // save it
    writeToFile(uploadedInputStream, uploadedFileLocation);

    String output = "File uploaded to : " + uploadedFileLocation;

    return Response.status(200).entity(output).build();

}

private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { 
  try { 
    OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); 
    int read = 0; 
    byte[] bytes = new byte[1024]; 
    out = new FileOutputStream(new File(uploadedFileLocation)); 
    while ((read = uploadedInputStream.read(bytes)) != -1) { 
      out.write(bytes, 0, read); 
    } 
    out.flush(); 
    out.close(); 
  } catch (IOException e) { 
    e.printStackTrace(); 
  } 
} 

Actually I got this [writeToFile] code from http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/

回答1:

If you want to write the file to the same server as the web server, you uploadedFileLocation should be a directory such as uploadedFileLocation = "/your_uploaded_file_direcoty/"; other than a HTTP URL.

If you want to write the file to a remote server via http, you can use some http framework.



回答2:

You're trying to write to a File called http://127.0.0.1:8080/Attachments/something.else. That is surely not going to work; according to the JavaDoc:

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Since you just print out your Exception stacktrace, but don't handle the failure, you don't get an indication that writing the file failed. Check your server log, there'll be a stacktrace stating the file you're trying to access cannot be found.

Instead, generate a filename, for example System.getProperty("java.io.tmpdir") + fileDetail.getFileName(), and write to that file. The JavaDoc for the File class states:

On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "C:\WINNT\TEMP".



标签: java rest tomcat