user_19240589
user_19240589

Reputation: 107

Not able to Insert image in database when form has enctype="multipart/form-data

I am facing issue inserting images in my database while using form enctype="multipart/form-data". I have tried using the Part class but that only return the name of the image, whereas I want the absolute path of the image. I have also tried using the below code

try {
    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            if(item.getFieldName().equals("txtPrdModel")){
                String ProductModel = item.getString();  
            }

            // ... (do your job here)
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getString());
            InputStream fileContent = item.getInputStream();
            // ... (do your job here)
        }
    }

This code gets the fieldName but getString doesn't return any value. I need to use enctype="multipart/form-data" and need the absolute path of the file I am trying to upload.

I am using netbeans 8.0.2 and servlet version is 3.1.

Upvotes: 0

Views: 92

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

For security reasons, the absolute path of the file isn't sent as part of the file name. You can only know the current name of the file that is uploaded to the server, so it's futile trying to obtain the absolute path that the file has on the client.

Once you have the file name and its binary data, use this info to store it in your specific path for files, in database or in another data source you're using.

Upvotes: 1

Related Questions