解决使用Spring Boot、Multipartfile上传文件路径错误问题

本文主要是介绍解决使用Spring Boot、Multipartfile上传文件路径错误问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.问题描述

  • 关键字: SpringMVC 4.2.4 、 Spring Boot 1.3.1 、Servlet 3.0 、文件上传
  • 报错信息: java.io.IOException: java.io.FileNotFoundException: /tmp/tomcat.273391201583741210.8080/work/Tomcat/localhost/ROOT/tmp/source/IMG_20160129_132623.jpg (No such file or directory)
  • 问题源码: transferTo方法报错
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    // 前端传入mulFileSource
    // 创建压缩前源文件
    File fileSourcePath = new File("tmp/source/");
    File fileSource = new File(fileSourcePath, mulFileSource.getOriginalFilename());
    if (!fileSourcePath.exists()) {
        fileSourcePath.mkdirs();
    }
    // 将接收得图片暂存到临时文件中
    mulFileSource.transferTo(fileSource);
    

2.问题分析

  • 首先,看源码中文件定义,相对路径,预期路径应该是项目路径/tmp/source/,但是报错确是一个系统临时文件路径(tomcat的)。
  • 其次,由于是transferTo方法报错,因此应该是该方法写入文件时报错,因此,我们跟入方法源码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {

//中间代码省略

/**
 * Spring MultipartFile adapter, wrapping a Servlet 3.0 Part object.
 */
@SuppressWarnings("serial")
private static class StandardMultipartFile implements MultipartFile, Serializable {

//中间代码省略

@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package org.apache.catalina.core;
/**
 * Adaptor to allow {@link FileItem} objects generated by the package renamed
 * commons-upload to be used by the Servlet 3.0 upload API that expects
 * {@link Part}s.
 */
public class ApplicationPart implements Part {

//中间代码省略

    @Override
    public void write(String fileName) throws IOException {
        File file = new File(fileName);
        if (!file.isAbsolute()) {
            file = new File(location, fileName);
        }
        try {
            fileItem.write(file);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
}
  • 源码一目了然,使用Servlet3.0的支持的上传文件功能时,如果我们没有使用绝对路径的话,transferTo方法会在相对路径前添加一个location路径,即:file = new File(location, fileName);。当然,这也影响了SpringMVC的Multipartfile的使用。
  • 由于我们创建的File在项目路径/tmp/source/,而transferTo方法预期写入的文件路径为/tmp/tomcat.273391201583741210.8080/work/Tomcat/localhost/ROOT/tmp/source/,我们并没有创建该目录,因此会抛出异常。

3.问题解决方案

  1. 使用绝对路径
  2. 修改location的值
    这个location可以理解为临时文件目录,我们可以通过配置location的值,使其指向我们的项目路径,这样就解决了我们遇到的问题。
    在Spring Boot下配置location,可以在main()方法所在文件中添加如下代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    /**
     * 文件上传临时路径
     */
     @Bean
     MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation("/app/pttms/tmp");
        return factory.createMultipartConfig();
    }
    

  3. Home  >   Spring 4

    Spring 4 MVC Single and Multiple File Upload Example with Tomcat

    By Arvind Rai,  August 09, 2014
    In this page we will learn how to upload a file in Spring 4 MVC. We are presenting the demo for single and multiple file upload. We are using XML less configurations. MultipartConfigElement Bean needs to be configured for file upload. In controller, method argument should be MultipartFile class for uploading the file. The JSP form, enctype must be set for multipart form data. Check the demo now.

    Software Used

    To run the file upload demo in Spring 4, get ready with below software. 
    1. JDK 7 
    2. Eclipse 
    3. Tomcat 7 
    4. Gradle 2.0 for Spring Boot

    Project Structure in Eclipse

    For better understanding, get the file location in eclipse how to put our classes and JSPs.
    Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat

    Controller Class: Use of MultipartFile

    In our example we are presenting demo for single and multiple file upload. So we have created two different methods for uploading the file. In single upload, the method should have the parameter as below with other parameters.
    @RequestParam("file") MultipartFile file 
    And for multiple file upload , the parameter should be as below
    @RequestParam("file") MultipartFile[]  file 
    Get the name of file from MultipartFile object and save it to your desired location. Find the controller. 
    FileUploadController.java
    package com.concretepage;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    @Controller
    public class FileUploadController {@RequestMapping(value="/singleUpload")public String singleUpload(){return "singleUpload";}@RequestMapping(value="/singleSave", method=RequestMethod.POST )public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file, @RequestParam("desc") String desc ){System.out.println("File Description:"+desc);String fileName = null;if (!file.isEmpty()) {try {fileName = file.getOriginalFilename();byte[] bytes = file.getBytes();BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));buffStream.write(bytes);buffStream.close();return "You have successfully uploaded " + fileName;} catch (Exception e) {return "You failed to upload " + fileName + ": " + e.getMessage();}} else {return "Unable to upload. File is empty.";}}@RequestMapping(value="/multipleUpload")public String multiUpload(){return "multipleUpload";}@RequestMapping(value="/multipleSave", method=RequestMethod.POST )public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){String fileName = null;String msg = "";if (files != null && files.length >0) {for(int i =0 ;i< files.length; i++){try {fileName = files[i].getOriginalFilename();byte[] bytes = files[i].getBytes();BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));buffStream.write(bytes);buffStream.close();msg += "You have successfully uploaded " + fileName +"<br/>";} catch (Exception e) {return "You failed to upload " + fileName + ": " + e.getMessage() +"<br/>";}}return msg;} else {return "Unable to upload. File is empty.";}}
    } 

    Configuration Class: Use of MultipartConfigElement Bean

    In the configuration class, we need to use bean for MultipartConfigElement and UrlBasedViewResolver. MultipartConfigElement supports the file upload where we can set max file size, max request size etc. MultipartConfigElement needs to be configured with Dispatcher servlet using WebApplicationInitializer . UrlBasedViewResolver defines the JSP location and file extension pattern of output. 
    AppConfig.java
    package com.concretepage;
    import javax.servlet.MultipartConfigElement;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.context.embedded.MultipartConfigFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.view.JstlView;
    import org.springframework.web.servlet.view.UrlBasedViewResolver;
    @Configuration
    @ComponentScan
    @EnableWebMvc
    @EnableAutoConfiguration
    public class AppConfig {@Beanpublic MultipartConfigElement multipartConfigElement() {MultipartConfigFactory factory = new MultipartConfigFactory();factory.setMaxFileSize("128KB");factory.setMaxRequestSize("128KB");return factory.createMultipartConfig();}@Bean  public UrlBasedViewResolver setupViewResolver() {  UrlBasedViewResolver resolver = new UrlBasedViewResolver();  resolver.setPrefix("/views/");  resolver.setSuffix(".jsp");  resolver.setViewClass(JstlView.class);return resolver;  }
    } 

    WebApplicationInitializer Class: Use of Dynamic.setMultipartConfig()

    WebApplicationInitializer is used when our application is not using web.xml. This supports all functionality which web.xml does. To supports file upload our dispatcher must be set for multipart config. 
    WebAppInitializer.java
    package com.concretepage;
    import javax.servlet.MultipartConfigElement;
    import javax.servlet.ServletContext;  
    import javax.servlet.ServletException;  
    import javax.servlet.ServletRegistration.Dynamic;  
    import org.springframework.web.WebApplicationInitializer;  
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;  
    import org.springframework.web.servlet.DispatcherServlet;  
    public class WebAppInitializer implements WebApplicationInitializer {public void onStartup(ServletContext servletContext) throws ServletException {  AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  ctx.register(AppConfig.class);  ctx.setServletContext(servletContext); ctx.refresh();Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  dynamic.addMapping("/");  dynamic.setLoadOnStartup(1);dynamic.setMultipartConfig(ctx.getBean(MultipartConfigElement.class));}  
    }  

    View: Use of enctype="multipart/form-data" and type="file"

    The JSPs are being used as views. To support file upload, form must be set with enctype for multipart form data and there should a file input text. We have two JSP. Find the JSP for single file upload. 
    singleUpload.jsp
    <html>
    <body>
    <h1>Single File Upload</h1><form method="post" enctype="multipart/form-data" action="singleSave">Upload File: <input type="file" name="file"><br /><br />Description: <input type="text" name="desc"/><br/><br/><input type="submit" value="Upload"> </form>
    </body>
    </html> 
    Find the JSP for multiple file Upload. We need to take care that each input type of file type must have same name, so that it could be accessed as an array. 
    multipleUpload.jsp
    <html>
    <body><h1> Multiple File Upload </h1><form method="post" enctype="multipart/form-data" action="multipleSave">Upload File 1: <input type="file" name="file"> <br/>Upload File 2: <input type="file" name="file"> <br/>Upload File 3: <input type="file" name="file"> <br/>Upload File 4: <input type="file" name="file"> <br/><br /><br /><input type="submit" value="Upload"> </form>
    </body>
    </html> 

    Spring Boot Jar Dependency using Gradle

    Find the gradle script for JAR dependency and creating WAR file of the project. Spring boot web and security are being used. 
    build.gradle
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'war'
    archivesBaseName = 'CP'
    repositories {mavenCentral()
    }
    dependencies {compile 'org.springframework.boot:spring-boot-starter-web:1.1.4.RELEASE'compile 'org.springframework.boot:spring-boot-starter-security:1.1.4.RELEASE'compile 'javax.servlet:jstl:1.2'compile 'commons-fileupload:commons-fileupload:1.3.1'
    }  

    Deploy in Tomcat 7 To Check Output

    Go to build directory in your project and inside lib you will get WAR file. Deploy in in tomcat and test. In our demo we are using tomcat 7. 
    Single File Upload Output
    For single upload use the URL as  http://localhost:8080/CP/singleUpload
    Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat
    Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat

    Multiple File Upload Output
    For multiple file upload use the URL as  http://localhost:8080/CP/multipleUpload
    Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat
    Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat

    Download Source Code

    spring-4-mvc-single-multiple-file-upload-example-with-tomcat.zip

    这篇关于解决使用Spring Boot、Multipartfile上传文件路径错误问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



    http://www.chinasem.cn/article/576174

    相关文章

    使用Python实现IP地址和端口状态检测与监控

    《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

    解决IDEA报错:编码GBK的不可映射字符问题

    《解决IDEA报错:编码GBK的不可映射字符问题》:本文主要介绍解决IDEA报错:编码GBK的不可映射字符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录IDEA报错:编码GBK的不可映射字符终端软件问题描述原因分析解决方案方法1:将命令改为方法2:右下jav

    Java 实用工具类Spring 的 AnnotationUtils详解

    《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

    Java controller接口出入参时间序列化转换操作方法(两种)

    《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

    Java中的StringBuilder之如何高效构建字符串

    《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

    使用Java将各种数据写入Excel表格的操作示例

    《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

    redis中使用lua脚本的原理与基本使用详解

    《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

    Java并发编程之如何优雅关闭钩子Shutdown Hook

    《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

    Maven中引入 springboot 相关依赖的方式(最新推荐)

    《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

    Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

    《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows