SpringBoot MultiPartFile To File 问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linfujian1999/article/details/77571918

之前在SpringMVC中没有碰到的问题如今在SpringBoot中成了一个问题,害我花了半天搞定。

问题再现:
截取部分代码

public String analyzeFile(MultipartFile file) {

        if(!file.isEmpty()) {
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
            File dir = new File(filePath);
            if(! dir.exists()) {
                dir.mkdir();
            }

            String path = filePath + file.getOriginalFilename();
            File tempFile = null;
            //save to the /upload path
            try {
                tempFile =  new File(path);

                file.transferTo(tempFile);

1)取得应用程序的path,加上upload 形成如: app directory/application/upload的路径并生成一个文件夹(没有的话),2)在该文件夹下生成一个和上传文件同名的文件
3)将上传文件MultiPartFile transfer to 上述文件中

springBoot本地测试是没有问题的(内嵌tomcat server),但打包上传到 glassfish server中去跑,却发现 在临时文件路径前又添加了generated/jsp的路径,造成了找不到文件的错误。

这个错误是file.transferTo(tempFile); 造成的,因为transferTo方法会默认在tempFile前添加一个新的路径,总之是个没用的路径。这样一来,tempFile path是有的,但前边加一个路径后,就造成了找不到文件的错误。这里的解决办法是不用TransferTo()方法,改用org.apache.commons.io.FileUtils

maven的pom.xml中添加

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
</dependency>

然后之前的代码改成

public String analyzeFile(MultipartFile file) {

        if(!file.isEmpty()) {
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
            File dir = new File(filePath);
            if(! dir.exists()) {
                dir.mkdir();
            }

            String path = filePath + file.getOriginalFilename();
            File tempFile = null;
            //save to the /upload path
            try {
                tempFile =  new File(path);
                        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

这样就将multipartfile正常转到tempFile中了。

猜你喜欢

转载自blog.csdn.net/linfujian1999/article/details/77571918