【问题标题】:Spring MVC - Copy image into WEB-INF/assets folderSpring MVC - 将图像复制到 WEB-INF/assets 文件夹中
【发布时间】:2018-06-12 10:57:05
【问题描述】:

我正在尝试将图像复制到 WEB-INF 文件夹内的 assets 文件夹中。以下代码成功将图像复制到项目外,但无法复制到 WEB-INF 文件夹内。

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

我从Http请求中得到了一个图片路径。

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

我已经在 dispatcher-servlet.xml

中映射了资源
<mvc:resources mapping="/static/**" location="/WEB-INF/assets/"/>

这是错误

信息:http:\localhost:8080\M.S.-Handloom-Fabrics\static\TueJun1216_27_54NPT20180.png(文件名、目录名或卷标语法不正确)

【问题讨论】:

    标签: image spring-mvc copy


    【解决方案1】:
    http://localhost:8080/M.S.-Handloom-Fabrics/static/"+imageName+".png"
    

    是一个 URL,而不是文件路径,因此作为 File 构造函数的参数是没有意义的。

    如果您将应用服务器配置为在部署时扩展您的 webapp,那么您可以使用 ServletContext.getRealPath,但正如 this SO post 的详细信息,您很可能不想这样做,因为您保存的文件将在重新部署时丢失。

    将它们保存在网络应用程序之外是可行的方法。

    【讨论】:

    • 你能给我一些关于如何使用ServletContext.getRealPath的建议吗?如果您有时间,请更正我上面的代码。谢谢
    • 我可以试试。您需要访问 http 请求。这个 copyFile 方法是从哪里调用的?一个小服务程序?一个弹簧@Controller?还是???
    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2011-08-15
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多