0

I am allowing the user to upload files to imgur hosting and get a link back. Everything seems to be working properly. However I am using

String itemName = item.getName();

It works perfectly in Internet Explorer and the browser of Eclipse. However when it comes to firefox and chrome it doesn't since due to browser security only the file name is retrieved in the input field. What is the workaround to get it to work?

My code:-

private void processlist(HttpServletRequest request, 
    HttpServletResponse response) {
        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.printStackTrace();
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                } else {
                    try {
                        String itemName = item.getName();


                        BufferedImage img = null;
                        try {
                            img = ImageIO.read(new File(itemName));
                        } catch (IOException e) {
                        }

                        String IMGUR_POST_URI = "https://api.imgur.com/3/upload";
                        String IMGUR_API_KEY = "mykeyyyyyyyyyyyy";
                        String projectname = "";
                        try {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            System.out.println("Writing image...");
                            ImageIO.write(img, "png", baos);
                            URL url = new URL(IMGUR_POST_URI);

                            System.out.println("Encoding...");
                            String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder
                                    .encode(Base64.encodeBase64String(baos.toByteArray()).toString(), "UTF-8");
                            data += "&" + URLEncoder.encode("key", "UTF-8") + "="
                                    + URLEncoder.encode(IMGUR_API_KEY, "UTF-8");

                            System.out.println("Connecting...");
                            URLConnection conn = url.openConnection();
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            conn.setRequestProperty("Authorization", "Client-ID " + IMGUR_API_KEY);
                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

                            System.out.println("Sending data...");
                            wr.write(data);
                            wr.flush();

                            System.out.println("Finished.");

                            // just display the raw response
                            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                            String line;
                            while ((line = in.readLine()) != null) {
                                JSONObject jObject = new JSONObject(line);
                                JSONObject data1 = jObject.getJSONObject("data");
                                projectname = data1.getString("link");
                                if (flagAccessed == false) {
                                    img1 = projectname;
                                } else {
                                    img2 = projectname;
                                }
                                System.out.print(projectname);

My JSP code is a simple form:-

<form action="UploadServlet" method="post" enctype="multipart/form-data" name="form1" id="form1" style="text-align:center;display:inline;">
<table border="1" style="text-align:center;">
                        <td><center>
                                Select image1: <input name="file" type="file" id="file" class="btn btn-dark btn-lg12">
                            </center></td>
                    </tr>

                    <tr>
                        <td><center>
                                Select image2: <input name="file" type="file" id="file" class="btn btn-dark btn-lg12">
                            </center></td>
                    </tr>
                    <tr>
                        <td align="center" style="margin-top: 5px;"></td>
                    </tr>

                </table>


            <br>
            <br>
            <input type="submit" name="Submit" value="Submit files" class="btn btn-dark btn-lg"/>

            </form>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
starry
  • 1
  • 8
  • I want to make sure I understand your question. Are you saying in IE `items` is a List of FileItem objects and in Firefox/Chrome it's a List of Strings? Or that the file contents aren't uploading in those browsers? – LAROmega Aug 05 '16 at 17:22
  • @LAROmega: In IE, the String itemName = item.getName(); returns... "C:\path\filename.jpg"... In short what I am trying to say is it returns the proper file path. So my code works. In Firefox and Chrome, String itemName = item.getName(); it returns only file name like filename.jpg, hence my img =null when trying to send it to imgur. – starry Aug 05 '16 at 17:35
  • I would say IE is the one being bad here. There's no reason the server needs to know the full path to the file on the client. But the fix should be easy. `if(item.getName() != null && item.getName().contains("\\/")` then parse it, else just use item.getName(). edit: I'm not 100% if you need to escape the forward slash or not. – LAROmega Aug 05 '16 at 17:39
  • @LAROmega: But i need the full file path. ImageIO.write(img, "png", baos); Where img is the full path of the image. – starry Aug 05 '16 at 18:28
  • Your `FileItem` object is from Apache Commons correct? If so then it should have an InputStream you can pass into ImageIO.read (ex: `ImageIO.read(item.getInputStream())`). Even in IE, the only time the way you're doing it will work is when the file is located on the server's hard drive in the same location as on the client (like in a development environment). – LAROmega Aug 05 '16 at 18:40
  • Thank you @LAROmega. That fixed the issue. – starry Aug 05 '16 at 18:50
  • No problem, glad to help. – LAROmega Aug 05 '16 at 18:57

1 Answers1

0

To summarize the fix: Changing img = ImageIO.read(new File(itemName)); to use img = ImageIO.read(item.getInputStream()); allows the server to access an InputStream of the image. Even though Internet Explorer is providing a full file path in the FileItem's name, that will only work in environments where the file is located in the exact same place on both the server and client, such as a development environment.

LAROmega
  • 488
  • 4
  • 13