简体   繁体   中英

Add images to the form in java

I want to add the image and the file with the same form in JSP. how should i do it? Here, i made the form as:

    <div id="user_img">
                <form name="form1" method="post" enctype="multipart/form-data" action="image_user_upload_db.jsp">
                <input type="file" name="poster" id="imagefile"/>
                <input type="submit" id="submit_img" value="submit"/>
                </form>
            </div>

and the jsp page which help in saving the image is:

 try{
    String ImageFile="";
    String itemName = "";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart){
    }
    else{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try{
            items = upload.parseRequest(request);
        }
        catch (FileUploadException e){
            e.getMessage();
        }

    Iterator itr = items.iterator();
    while (itr.hasNext()){
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()){
            String name = item.getFieldName();
            String value = item.getString();
            if(name.equals("poster")){
                ImageFile=value;
            }
        }
        else{
            try{
                itemName = item.getName();
                File savedFile = new     File(config.getServletContext().getRealPath("/")+"\\img\\user_img\\"+itemName);
                item.write(savedFile);
            }
            catch (Exception e){
                out.println("Error"+e.getMessage());
            }
        }
    }
    try{
        String str="update user_info set img_name='"+itemName+"' where user_id=?";
        PreparedStatement ps=con.prepareStatement(str);
        ps.setInt(1,id1);
        int rs1=ps.executeUpdate();
        response.sendRedirect("profile.jsp");
    }
    catch(Exception el){
        out.println("Inserting error"+el.getMessage());
    }   
}
}

I want this form to take the other input type also, but as i add another input type to the form, it gives error.

you can get their values take a closer look at this code

if (item.isFormField()){
            String name = item.getFieldName();
            String value = item.getString();
            if(name.equals("poster")){
                ImageFile=value;
            }
 }

to get the other field values just use item.getFieldName() then check if it is the field name that you are looking for then store it in a variable

String otherField;

if(name.equals("otherField")){

   otherField = item.getString();
}

Use the following code in your action page,

<%

String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
saveFile=config.getServletContext().getRealPath("/")+"user_upload\\"+saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

}

%>

Here 'user_upload' is a folder name, in which the uploaded file will be stored.

Before executing this code, you have to create a folder with the name 'user_upload' in your project directory.

NB:- You can change folder name.

use following code




DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE); // sets maximum size of request (include file + form data)
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                for (FileItem item : formItems) {
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        System.out.println("item.getFieldName() => "+item.getFieldName());
                        String fileAttr[] = fileName.split("\\.");
                        String newFileName = fileAttr[0];
                        int i = 1;
                        while (true) {
                            File f = new File(uploadPath + "\\" + newFileName + "." + fileAttr[1]);
                            if (f.exists()) {
                                newFileName = fileAttr[0] + i;
                                i++;
                            } else {
                                fileName = newFileName + "." + fileAttr[1];
                                break;
                            }
                        }
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        item.write(storeFile);
                        request.setAttribute("message","Upload has been done successfully!");
                    } else {
                        System.out.println("1 item.getFieldName() => "+item.getFieldName());
                        if("description1".equalsIgnoreCase(item.getFieldName())){
                            //this part is for other field except file field
                        }
                    }
                }
            }

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