0

Servlet code:

package net;

import SQLBean.DbBean;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.System.out;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

public class FileUploadServlet extends HttpServlet {

    //private static final String UPLOAD_DIRECTORY = "uploads";
    private static final String UPLOAD_DIRECTORY = "/stohere/uploads/imgdogs";

    String file1 = "";
    String file2 = "";
    @Override


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //int rowcount;
        //response.getOutputStream().println("count is ");
        try {
            Connection connection = DbBean.getInstance().getConnection();
            String cquery = "";
            cquery = "SELECT count(petid) FROM petimg WHERE petid > ?";
            PreparedStatement cs = connection.prepareStatement(cquery);
            //ResultSet r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM FieldMaster");
            cs.setInt(1, 0);
            //PreparedStatement cs = connection.prepareStatement(cquery);
            ResultSet rc = cs.executeQuery();

            int rowcount;
            rowcount = 0;
            while (rc.next()) {
                rowcount = rc.getInt(1);
            }
            rc.close();
            cs.close();

            for (int i = 0; i < 2; i++) {

                int newcount1 = rowcount + 1;
                String thiscount1 = Integer.toString(newcount1);

                //response.getOutputStream().println("count is " + thiscount1);
                //break;
                //getset.gset cv = new getset.gset();
                String uploadPath = UPLOAD_DIRECTORY;
                if (i == 0) {
                    file1 = "";
                    Part filePart = request.getPart("uploadFile1");
                    InputStream fileInputStream = filePart.getInputStream();

                    if (fileInputStream == null) {
                        break;
                    }
                    if (request.getPart("uploadFile1").getSize() <= 0) {
                        break;
                    }

                    //String uploadPath = getServletContext().getRealPath("")
                           // + File.separator + UPLOAD_DIRECTORY;





                    String filename1 = filePart.getSubmittedFileName();

                    int dot = filename1.lastIndexOf('.');
                    String filebase1 = (dot == -1) ? filename1 : filename1.substring(0, dot);
                    String extension1 = (dot == -1) ? "" : filename1.substring(dot + 1);

                    //String file = filename1.substring(0, filename1.lastIndexOf('.'));
                    //here
                    File fileToSave = new File(uploadPath + "/" + filebase1 + thiscount1 + "." + extension1);
                    //File fileToSave = new File(uploadPath + "/" + filebase1 + thiscount1 + extension1);

                    file1 = filebase1 + thiscount1 + "." + extension1;
                    //response.getOutputStream().println(fileToSave);
                    Files.copy(fileInputStream, fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    request.setAttribute("file1", file1);
                }

                if (i == 1) {
                    file2 = "";
                    int newcount2 = rowcount + 2;

                    String thiscount2 = Integer.toString(newcount2);

                    Part filePart = request.getPart("uploadFile2");
                    InputStream fileInputStream = filePart.getInputStream();
                    if (fileInputStream == null) {
                        break;
                    }
                    String fileName2 = filePart.getName();
                    if (request.getPart("uploadFile2").getSize() <= 0) {
                        break;
                    }

                    //String uploadPath = getServletContext().getRealPath("")
                            //+ File.separator + UPLOAD_DIRECTORY;
                    String filename2 = filePart.getSubmittedFileName();

                    int dot = filename2.lastIndexOf('.');
                    String filebase2 = (dot == -1) ? filename2 : filename2.substring(0, dot);
                    String extension2 = (dot == -1) ? "" : filename2.substring(dot + 1);

                    File fileToSave = new File(uploadPath + "/" + filebase2 + thiscount2 + "." + extension2);
                    file2 = filebase2 + thiscount2 + "." + extension2;
                    Files.copy(fileInputStream, fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    request.setAttribute("file2", file2);
                }                   //break;  break here.

            }

            String myname = request.getParameter("myname");
            String species = request.getParameter("species");

            request.setAttribute("myname", myname);
            request.setAttribute("species", species);
            request.setAttribute("message",
                    "Upload has been done successfully!");

            String sql = "";
            sql = "insert into petimg (petname, species, pic1, pic2) values(?, ?, ?, ?)";
            PreparedStatement insertcs = connection.prepareStatement(sql);
            insertcs.setString(1, myname);
            insertcs.setString(2, species);
            insertcs.setString(3, file1);
            insertcs.setString(4, file2);
            insertcs.executeUpdate();
            insertcs.close();

        } catch (Exception e) {

            response.getOutputStream().println("Exception is ;" + e);

        }

        RequestDispatcher dispatcher = request.getRequestDispatcher("/message2.jsp");
        if (dispatcher != null) {
            dispatcher.forward(request, response);
        }

        //response.getOutputStream().println("<p>Upload another file <a href=\"http://localhost:8080/index.html\">here</a>.</p>");  
    }
}

Included are two images, first is Firefox: See https://i.stack.imgur.com/rwbyO.jpg

And second is Edge: See https://i.stack.imgur.com/bMvMz.jpg

Firefox is just getting ann.JPG

Edge gets C:\Users\jimwin7a\Pictures\ann.JPG

Here is the exact error:

Exception is ;java.nio.file.InvalidPathException: Illegal char <:> at index 26: \stohere\uploads   \imgdogs\C:Usersjimwin7aPicturesann7.JPG

As you can see Edge is getting: \C:Usersjimwin7aPicturesann7.JPG

So how do I re-work the servlet to work in Edge also?

  • I think the issue is due to the backslashes in the path in Edge. How do you get the path of the file? You could try to check if you could replace the backslashes with double backslashes or `/` when getting the file path. Besides, you could try to use `Paths.get()` to get the file path. For more information, you could refer to [this thread](https://stackoverflow.com/questions/9834776/java-nio-file-path-issue) and [this thread](https://stackoverflow.com/questions/38887853/java-nio-file-invalidpathexception-with-getpath/38888561). – Yu Zhou Jun 02 '20 at 06:56
  • The problem is, in Edge I get this: C:Usersjimwin7aPicturesann.JPG, but in Chrome and FF I just get ann.JPG which works. With using Part filePart = request.getPart("uploadFile1"); and InputStream fileInputStream = filePart.getInputStream(); does not work on Edge. I do have another servlet using Apache commons that does work. But I'd like to get this working, I need just file and extension, not the full path also. Thanks – Jim Whitaker Jun 03 '20 at 00:31
  • You can't force Edge to only show the file name. That's by design in different browsers. So we can't change what the browser sends. Is your working servlet using Apache commons [this](http://commons.apache.org/proper/commons-fileupload/faq.html#whole-path-from-IE)? If so, then I think there's no any other server solution. Maybe you could consider to get the file name using JavaScript at the front then send it to server. – Yu Zhou Jun 03 '20 at 08:27

1 Answers1

0

I hope this helps someone, I got it working.

First I added this:

String fileName = getFileName(filePart).toString();

getFileName is from another S.O. article:

    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        System.out.println("content-disposition header= "+contentDisp);
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }

But to just get file.jpg i.e., ann.jpg I run through another function:

this line

String acfilename = fixSubmittedFileName(fileName);

function is:

    private static String fixSubmittedFileName(String fileName) {

        String nfname = fileName;

        nfname = nfname.replace("\\", "/");
        int dot = nfname.lastIndexOf('/');
        String afname = (dot == -1) ? nfname : nfname.substring(dot + 1);
        return afname;


    }

Test on Chrome, Edge, Firefox, and Ie 11, works.

Thanks for answers and help.