0

My application used to work: I am using PrimeFaces 6, but I want to upload a file using Servlet version 3 and ajax.

I used this sources for developing my code:

using two forms in a JSF template

Upload a file using Servlet 3.0

Mozilla Guide for using ajax to upload an image - part I

Mozilla Guide for using ajax to upload an image - part II

In my template (view) I have two forms. The first one is for gathering customer data, the second one is the form I use to upload a picture for that customer using ajax (Java script) and servlet version 3. Everything works fine with the exception that in the servlet responsible for processing the image I have uploaded I am getting a null reference to the to the Part. Here my code:

1.) An extract from the view (PrimeFaces facelet):

 <h:form id="newCustomerformId">
  <!-- rest of code not shown here -->
   <p:commandButton type="submit" value="Create Customer"
                                    icon="ui-icon-check"
                                    actionListener="#   {newCustomerBean.saveNewCustomer}"
                                    update = "@form"
                                    oncomplete="ajaxUploadFile();"/>            

    </h:form>

    <h:form id="uploadImageForNewCustomerformId"
        enctype="multipart/form-data">
        <div id="dropzone">
            <img id="librarypreview" src='' alt='library'
                    style="width: 280px; height: 160 px;" />
             <select name="top5" id="flist" size="5" onchange="previewFile()">
             </select>
            <output id="list"> </output>
        </div>
            <input id="fileInput" type="file" multiple="multiple"></input>
            <span id="uploadStatusId"></span>
   </h:form>

2.) My ajaxUploadFile() JavaScript function:

function ajaxUploadFile() {
    var form = document.getElementById('uploadImageForNewCustomerformId');

    if (form == null)
        return;

     var formData = new FormData(form);

     for (var i = 0; i < fileList.length; i ++){
       //append a File to the FormData object
       formData.append("file", fileList[i], fileList[i].name);
     }

    var uploadStatusOutput = document.getElementById("uploadStatusId");
    var request = new XMLHttpRequest();
    request.open("POST", "/javakurs3-biliothek-jsf-mobile/fileUpload");
    request.responseType = 'text';
    request.onload = function(oEvent) {

        if (request.readyState === request.DONE) {
            if (request.status === 200) {
                if (request.responseText == "OK") {
                    form.action = "/javakurs3-biliothek-jsf-mobile/pages/customers.jsf";
                    form.submit();
                    return;
                }
            } 
            uploadStatusOutput.innerHTML = "Error uploading image";

        } // request.readyState === request.DONE

    };  // function (oEvent)

    request.send(formData);
};

3.) My servlet version 3 to process the uploaded image:

@WebServlet("/fileUpload")
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {



    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {

        HttpSession session = request.getSession(false);

        System.out.println(session);

        Long savedKundeId = (Long) session.getAttribute(NewCustomerBean.SESSION_ATTRIBUTE_CUST_ID);     

        Part filePart = null;
        PrintWriter pw = null;
        try {
            filePart = request.getPart("file");

My problem is that filePart = request.getPart("file"); returns null.

How can I solve this?

thank you and kind regards: Alex

Kukeltje
  • 12,223
  • 4
  • 24
  • 47
Alex Mi
  • 1,409
  • 2
  • 21
  • 35

2 Answers2

1

@Java Samurai: Thank you for your advice: I applied it to my code and now it works as expected. Here is the "solution":

    Part filePart = null;
    String fileNamer = null;


    try {
        for (Part fPart : request.getParts()){
            if (fPart.getName()!=null && fPart.getName().equals("file") && StringUtils.isNotEmpty(fPart.getSubmittedFileName())){
                fileNamer =  fPart.getSubmittedFileName();
                filePart = fPart;
                break;
            }
        }
Alex Mi
  • 1,409
  • 2
  • 21
  • 35
0

You should get all the parts with getParts and check the names. I think "