0

I am trying to copy image into assets folder inside WEB-INF folder. Following code successfully copy images outside the project but can't copy inside WEB-INF folder.

public static void copyFile(String source, String destination) throws IOException {
        try {
            File sourceFile = new File(source);
            File destinationFile = new File(destination);

            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

            int bufferSize;
            byte[] bufffer = new byte[512];
            while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                fileOutputStream.write(bufffer, 0, bufferSize);
            }
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            throw new IOException(e.getMessage());
        }
    }

I get a image path from Http request.

CopyFile.copyFile(imageUrl, "http://localhost:8080/M.S.-Handloom-Fabrics/static/"+imageName+".png");

I have mapped the resources in dispatcher-servlet.xml

<mvc:resources mapping="/static/**" location="/WEB-INF/assets/"/>

Here is the error

Info: http:\localhost:8080\M.S.-Handloom-Fabrics\static\TueJun1216_27_54NPT20180.png (The filename, directory name, or volume label syntax is incorrect)

Chris Hadfield
  • 494
  • 1
  • 7
  • 34

1 Answers1

0
http://localhost:8080/M.S.-Handloom-Fabrics/static/"+imageName+".png"

is a URL, not a file-path, and is therefore meaningless as a parameter to the File constructor.

IF you configured your app server to explode your webapp on deploy then you could use ServletContext.getRealPath but as this SO post details nicely you most likely do not want to do this as your saved files will be lost upon re-deploy.

Saving them outside of the web app is the way to go.

Paul Warren
  • 2,411
  • 1
  • 15
  • 22
  • Can you give me some suggestion about how to use `ServletContext.getRealPath`. If you have a time please correct my above code. Thanks – Chris Hadfield Jun 13 '18 at 14:29
  • I can try. You need access to the http request. Where is this copyFile method called from? A servlet? A Spring @Controller? Or ??? – Paul Warren Jun 14 '18 at 15:38