欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springboot文件上传

程序员文章站 2022-06-03 13:24:23
...

关于Springboot的文件上传

配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>work</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.8</version>
        </dependency>

		 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>		
		<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
    	</dependency>
		 <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

DemoController.java文件访问upload.html页面

package com.example.work.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class DemoController{
    @RequestMapping("/test")
    public String picUpload(){
        return "upload";//访问upload.html
    }
}

file_testController.java文件提交文件上传返回是否成功

package com.example.work.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import com.example.work.pojo.testJsonData;
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.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件上传
 * 
 */
@RestController//返回json格式的数据
public class file_testController {
    
    // @RequestMapping("/test")
    // public String index() {
    //     return "upload";
    // }
    
    private static final String filePath = "E:/damo/Springboot_work/work/src/main/resources/static";

    @RequestMapping(value="/upload", method= RequestMethod.POST)
    //@ResponseBody
    public testJsonData upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String name = request.getParameter("name");
        System.out.println("用户名" + name);

        // 获取文件名
        String filename = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //上传文件后路径
        filename = UUID.randomUUID() + suffixName;
        //实例化文件对象
        File dest = new File(filePath, filename);

        // 判断路径是否存在,如果不存在则创建
		if(!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
        }
        
        try {
            file.transferTo(dest);
            return new testJsonData(0,"success to upload");
        } catch (IllegalStateException | IOException e) {
           
            e.printStackTrace();
        }
       
        return new testJsonData(-1,"fail to upload");
    }

}

testJsonData.java返回状态码和消息

package com.example.work.pojo;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class testJsonData implements Serializable
{

    /**
     *返回
     */
    private static final long serialVersionUID = 1L;
    //状态码0或-1
    private int code;
    //结果    
    private String msg;
}

upload.html这个文件放在templates文件夹下

<!DOCTYPE html>
<html>
<head>
    <title>upload</title>
    <meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
</head>
<body>
    <!--文件上传必须用multipart/form-data-->
    <form enctype="multipart/form-data" method="POST" action='/upload'>
        文件:<input type="file" name="file"/>
        名字:<input type="text" name="name"/>
        <input type="submit" value="上传"/>       
    </form>
</body>
</html>

运行结果
Springboot文件上传
Springboot文件上传