解决使用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

    相关文章

    MybatisGenerator文件生成不出对应文件的问题

    《MybatisGenerator文件生成不出对应文件的问题》本文介绍了使用MybatisGenerator生成文件时遇到的问题及解决方法,主要步骤包括检查目标表是否存在、是否能连接到数据库、配置生成... 目录MyBATisGenerator 文件生成不出对应文件先在项目结构里引入“targetProje

    Linux使用fdisk进行磁盘的相关操作

    《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存

    C#使用HttpClient进行Post请求出现超时问题的解决及优化

    《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

    SpringBoot使用Apache Tika检测敏感信息

    《SpringBoot使用ApacheTika检测敏感信息》ApacheTika是一个功能强大的内容分析工具,它能够从多种文件格式中提取文本、元数据以及其他结构化信息,下面我们来看看如何使用Ap... 目录Tika 主要特性1. 多格式支持2. 自动文件类型检测3. 文本和元数据提取4. 支持 OCR(光学

    Java内存泄漏问题的排查、优化与最佳实践

    《Java内存泄漏问题的排查、优化与最佳实践》在Java开发中,内存泄漏是一个常见且令人头疼的问题,内存泄漏指的是程序在运行过程中,已经不再使用的对象没有被及时释放,从而导致内存占用不断增加,最终... 目录引言1. 什么是内存泄漏?常见的内存泄漏情况2. 如何排查 Java 中的内存泄漏?2.1 使用 J

    JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

    《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

    Linux使用dd命令来复制和转换数据的操作方法

    《Linux使用dd命令来复制和转换数据的操作方法》Linux中的dd命令是一个功能强大的数据复制和转换实用程序,它以较低级别运行,通常用于创建可启动的USB驱动器、克隆磁盘和生成随机数据等任务,本文... 目录简介功能和能力语法常用选项示例用法基础用法创建可启动www.chinasem.cn的 USB 驱动

    Java 字符数组转字符串的常用方法

    《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu

    C#使用yield关键字实现提升迭代性能与效率

    《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭

    使用SQL语言查询多个Excel表格的操作方法

    《使用SQL语言查询多个Excel表格的操作方法》本文介绍了如何使用SQL语言查询多个Excel表格,通过将所有Excel表格放入一个.xlsx文件中,并使用pandas和pandasql库进行读取和... 目录如何用SQL语言查询多个Excel表格如何使用sql查询excel内容1. 简介2. 实现思路3