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

做~自己de王妃 提交于 2019-12-28 16:18:25

问题


I want to upload an Image using JSP Servlet and ejb 3.0


回答1:


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.



来源:https://stackoverflow.com/questions/2827138/how-to-upload-an-image-using-jsp-servlet-and-ejb-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!