开发者

How to upload an image using JSP -Servlet and EJB 3.0 [duplicate]

开发者 https://www.devze.com 2022-12-30 08:18 出处:网络
This question already has answers here: How can I upload files to a server using JSP/Servlet? (14 answers)
This question already has answers here: How can I upload files to a server using JSP/Servlet? (14 answers) Closed 7 years ago.

I开发者_高级运维 want to upload an Image using JSP Servlet and ejb 3.0


To start, to select a file for upload using JSP you need at least a HTML <input type="file"> element which will display a file browse field. As stated in the HTML forms spec you need to set the request method to POST and the request encoding to multipart/form-data in the parent <form> element.

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>

Because the aforementioned request encoding isn't by default supported by the Servlet API before Servlet 3.0 (which I don't think you're using because EJB 3.0 is part of Java EE 5.0 which in turn contains Servlet 2.5 only), you won't see anything in the request parameter map. The request.getParameter("file") would return null.

To retrieve the uploaded file and the other request parameters in a servlet, you need to parse the InputStream of the HttpServletRequest yourself. Fortunately there's a commonly used API which can take the tedious work from your hands: Apache Commons FileUpload.

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
    if (!item.isFormField()) {
        // <input type="file">
        System.out.println("Field name: " + item.getFieldName());
        System.out.println("File name: " + item.getName());
        System.out.println("File size: " + item.getSize());
        System.out.println("File type: " + item.getContentType());
    } else {
        // <input type="text|submit|hidden|password|button">, <select>, <textarea>, <button>
        System.out.println("Field name: " + item.getFieldName());
        System.out.println("Field value: " + item.getString());
    }            
}

Basically you just need to get the InputStream from the FileItem object and write it to any OutputStream to your taste using the usual Java IO way.

InputStream content = item.getInputStream();

Alternatively you can also write it directly:

item.write(new File("/uploads/filename.ext"));

At their homepage you can find lot of code examples and important tips&tricks in the User Guide and Frequently Asked Questions sections. Read them carefully.

0

精彩评论

暂无评论...
验证码 换一张
取 消