1

I'm trying to develop a file upload function on AWS.

I wrote a servlet to process post request, and the framework is shown below:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    boolean isMulti = ServletFileUpload.isMultipartContent(request);
    if (isMulti) {
        ServletFileUpload upload = new ServletFileUpload();

        try {
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream inputStream = item.openStream();
                if (item.isFormField()) {

                } else {
                    String fileName = item.getName();
                    if (fileName != null && fileName.length() > 0) {

                        //read stream of file uploaded

                        //store as a temporary file

                        //upload the file to s3
                    }
                }
            }
        } catch (Exception e) {
        }
    }

    response.sendRedirect("location of the result page");
}

I think these classes should be used to upload files. I tried but in S3, the size of the file is always 0 byte. Are there any other ways to upload file with multiple parts?

  1. InitiateMultipartUploadRequest
  2. InitiateMultipartUploadResult
  3. UploadPartRequest
  4. CompleteMultipartUploadRequest

I refer to the code http://docs.aws.amazon.com/AmazonS3/latest/dev/llJavaUploadFile.html

4

1 回答 1

3

I guess you are clubbing two things - one is getting the entire file to your app container (on the tomcat where your servlet is running) and the other is uploading the file to S3.

If you are able to achieve the first of the above tasks (you should have the file as a java.io.File object), the second task should be straightforward:

AmazonS3 s3 = new AmazonS3Client(awsCredentials);
s3.putObject(new PutObjectRequest(bucketName, key, fileObj));

This is S3's simple upload. S3 Multipartupload is where you divide the whole file into chunks and upload each chunk in parallel. S3 gives two ways to achieve a multipartupload.

  • Low level - where you take of chunking and uploading each part. This uses the classes you mentioned like InitiateMultipartUploadRequest
  • High level - In this S3 abstracts the process of chunking/uploading etc. using a TransferManager class
于 2013-03-31T14:20:35.120 回答