0

I use Servlet 3.0, PrimeFaces 6.0, WildFly 8.2, Eclipse Neon, Mozilla or Chrome browsers. Despite following these nice links below:

Oracle Tutorial on File Upload

GitHub: getting the original file name example

I am still not able to determine the actual file name of an uploaded file. My problem is that in the below mentioned servlet the method call:

String fileNamer = getFileName(filePart);

gives me back NULL for the file name, i.e. fileNamer is null. What am I doing wrong? Please help:

1.) Here is my controller (servlet):

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


private String getFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            return cd.substring(cd.indexOf('=') + 1).trim()
                    .replace("\"", "");
        }
    }
    return null;
}

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

        HttpSession session = request.getSession(false);
        Long savedKundeId = (Long) session.getAttribute(NewCustomerBean.SESSION_ATTRIBUTE_CUST_ID);     

        Part filePart = null;
        PrintWriter pw = null;  
        try {
            filePart = request.getPart("uploadImageForNewCustomerformId");
            String fileNamer = getFileName(filePart); 
            // rest of code not shown here

2.) My view (Prime Faces 6.0 facelet):

<h:form id="newCustomerformId">

<!-- rest of code not shown -->
            <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" name = "file"></input>
                            <span id="uploadStatusId"></span>
                        </h:form>

3.) My Java Scipt function for ajax-uploading the file:

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);


        };
Alex Mi
  • 1,409
  • 2
  • 21
  • 35
  • That's a lot of code and you don't seem to have boiled down the problem at all. Are you indeed implying that the `fileList[i].name` in JavaScript code isn't null/empty? Are you indeed implying that this problem doesn't occur when you don't use PrimeFaces/JSF? Nonetheless, I can't ignore the impression that you're overcomplicating things here. Given that you're already using JSF, why falling back to plain vanilla JS+Servlet? Perhaps this is what you actually wanted to ask: https://stackoverflow.com/q/38018632 – BalusC Jan 01 '18 at 12:51
  • @BalusC fileList[i].name in Java script is NOT null and is NOT empty. Falling back to plain vanilla JS+Servlet is done in order to give the user the opportunity to preview the file (with the help of JS) BEFORE uploading it. This would not be the case if only prime faces is used, or am I wrong? – Alex Mi Jan 01 '18 at 12:52
  • PrimeFaces upload has preview functionality – Kukeltje Jan 01 '18 at 18:49
  • Huh? You're not doing preview using JS, but you're actually uploading the file using JS. – BalusC Jan 01 '18 at 22:02
  • @BalusC, yes, correct, is there anything wrong with using JavaScript for preview of an image and afterwards for uploading it? – Alex Mi Jan 06 '18 at 15:37

1 Answers1

0

I was finally was able to solve the problem. As BalusC correctly put it, I am not only doing a preview of the image using Java Script, but also uploading it using Java script. This caused confusion, as PrimeFaces supports an image preview and an image upload using their custom, own tag, as shown here .

p:fileUpload showcase

The problem using this p:fileUpload is that it has its own button for the image submission, or upload. However, I want to both submit my newly entered customer data AND upload the image using EXACTLY ONE button and button click.

The solution to my requirement is that I used the following code in my ImageUploadServlet

for (Part fPart : request.getParts()){
                if (fPart.getName()!=null && fPart.getName().equals("file") && StringUtils.isNotEmpty(fPart.getSubmittedFileName())){
                    fileNamer =  fPart.getSubmittedFileName();
                    filePart = fPart;
                    break;
                }
            } 

instead of the code I mentioned in my question:

private String getFileName(Part part) {
    for (String cd : part.getHeader("content-disposition").split(";")) {
        if (cd.trim().startsWith("filename")) {
            return cd.substring(cd.indexOf('=') + 1).trim()
                    .replace("\"", "");
        }
    }
    return null;
}
Alex Mi
  • 1,409
  • 2
  • 21
  • 35