简体   繁体   中英

Cannot upload a file to amazon S3 bucket with localhost in eclipse

I am trying to upload a file to Amazon S3 bucket through a web page.

Created a "Dynamic Web Project" in Eclipse with apache tomcat server. Create a JSP, Servlet and Java files. I have used aws-java-sdk-1.11.335.jar file. Tried to upload a image file by submit button click, Class not Found Exception is occurred. Can some one help to resolve this issue.

Here is Code for JSP, Servlet and Class Files:

index.jsp :

<form method="post" action="UploadFileServlet" enctype="multipart/form-data">
       <input type="submit" value="Upload" />
</form>

UploadFileServlet.java :

@WebServlet("/UploadFileServlet")
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


public UploadFileServlet() {
    super();
}


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    UploadFilestoAWSS3 uploadfilestoawss3 = new UploadFilestoAWSS3();
    uploadfilestoawss3.UploadFiles();

    PrintWriter out = response.getWriter();
    out.print("Files are uploaded to Bucket");

}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

UploadFilestoAWSS3.java

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest;
import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest;
import com.amazonaws.services.s3.model.InitiateMultipartUploadResult;
import com.amazonaws.services.s3.model.PartETag;
import com.amazonaws.services.s3.model.UploadPartRequest;
import com.amazonaws.services.s3.model.UploadPartResult;

public class UploadFilestoAWSS3 {

    public void UploadFiles() throws IOException {
        String clientRegion = "region";
        String bucketName = "bucket name";
        String filePath = "C:\\Users\\......\\imagefile.jpg";

        File file = new File(filePath);
        String keyName = file.getName();
        long contentLength = file.length();
        long partSize = 10 * 1024 * 1024; // Set part size to 10 MB. 

        try {
            BasicAWSCredentials awsCreds = new BasicAWSCredentials("Access Key", "Secret Key");
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                                .withRegion(clientRegion)
                                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                                .build();

        List<PartETag> partETags = new ArrayList<PartETag>();

        InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, keyName);
        InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);

        long filePosition = 0;
        for (int i = 1; filePosition < contentLength; i++) {
            partSize = Math.min(partSize, (contentLength - filePosition));

            UploadPartRequest uploadRequest = new UploadPartRequest()
                    .withBucketName(bucketName)
                    .withKey(keyName)
                    .withUploadId(initResponse.getUploadId())
                    .withPartNumber(i)
                    .withFileOffset(filePosition)
                    .withFile(file)
                    .withPartSize(partSize);

            UploadPartResult uploadResult = s3Client.uploadPart(uploadRequest);
            partETags.add(uploadResult.getPartETag());

            filePosition += partSize;
        }

        CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketName, keyName,
                initResponse.getUploadId(), partETags);
        s3Client.completeMultipartUpload(compRequest);
    }
    catch(AmazonServiceException e) {
        e.printStackTrace();
    }
    catch(SdkClientException e) {
        e.printStackTrace();
    }

}

}

Error is:

Type Exception Report

Message Servlet execution threw an exception

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)


Root Cause
java.lang.NoClassDefFoundError: com/amazonaws/AmazonServiceException
com.shiva.amazonaws.UploadFileServlet.doGet(UploadFileServlet.java:51)
com.shiva.amazonaws.UploadFileServlet.doPost(UploadFileServlet.java:64)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)


Root Cause
java.lang.ClassNotFoundException: com.amazonaws.AmazonServiceException
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1292)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1121)
com.shiva.amazonaws.UploadFileServlet.doGet(UploadFileServlet.java:51)
com.shiva.amazonaws.UploadFileServlet.doPost(UploadFileServlet.java:64)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

The problem is that some of the Amazon Web Services SDK classes are not found, specifically com.amazonaws.AmazonServiceException , which is the basic exception type for the AWS SDK - indicating that likely all of the AWS SDK files are missing from the Java classpath.

Please note that the file aws-java-sdk-1.11.335.jar is not the entire AWS SDK (as one might have thought) and only contains some metadata files. The AWS Java SDK is split into multiple artifacts - because it is so big you don't want to use a single JAR file with all the classes, you want to only take the SDK for the specific services you are using.

Because you are using S3, you probably just want the S3 JAR, and its dependencies, as can be seen in the Maven repository page for the AWS S3 SDK . Please note that one of the dependencies is aws-java-sdk-core which is where the com.amazonaws.AmazonServiceException class lives.

You can also see all the dependencies (and navigate the directories to collect all the files that you need) in the POM file under http://central.maven.org/maven2/com/amazonaws/aws-java-sdk-s3/1.11.335/ .

Generally, because of the complex dependency structures that are common these days, it is recommended to not download JARs manually and put them into one by one in to the Eclipse build path, but to use Maven instead.

If you have a standard Java project in eclipse, you can right-click the project name in the package explorer then choose "Configure"->"Convert to Maven project" and fill in some details in the dialog that opens(*). After that compeletes, Eclipse will create a pom.xml file in the root of your project - open it, and you will get a custom editor to set up your dependencies. Click on the tab labeled "Dependencies" and then on "Add" and you should be able to search for aws-java-sdk-s3 , add it to your dependency list and then Maven will automatically download all the required JAR files and add them automatically to your build path.

*) "Group ID" is generally the top package name of your project, which should look like a domain name in reverse - for example my domain is geek.co.il , so my Group ID will be il.co.geek ; "Artifact ID" is a single word identifier for your project, for example my-project .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM