Springboot AJAX 实现表单 文件上传

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax实现表单文件上传</title>
     
    <script type="text/javascript" src="../static/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
       function doclick(){
           var form = new FormData(document.getElementById("loginForm"));
           console.log(form);
           $.ajax({
               url:"/user/upload",
               data:form,
               cache : false,
               contentType : false, //必需,因为我们在表单上填加了`enctype="multipart/form-data"`,所以这里设为false
               processData : false,//必需,默认为true,发送的数据转为Object,适合于"application/x-www-form-urlencoded",这里设为false
               type:"post",
               success:function (data) {
                   alert(data)
               },
               error:function () {
                   alert("系统有问题!")
               }
           })
       }
    </script>
</head>
<body>
<form action="#" method="post" enctype="multipart/form-data" id="loginForm">
    <label>上传图片</label>
    <input type="file" name="imgFile" id="head_picture_file"/>
     name:<input type="text" name="name">
    <br>
     pwd:<input type="text" name="pwd"/>
    <button type="button" onclick="doclick()">提交</button>
</form>

</body>
</html>

视图层 controller

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile imgFile,String name,String pwd){
        System.out.println(name+"|"+pwd+"|");
        String msg=userLogonService.UploadAvatar(imgFile);
        return msg;
    }
  }  

工具类UploadUtils

public class UploadUtils {
    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下(SpringBoot 默认)
    public final static String IMG_PATH_PREFIX = "static/image/user";

    public static File getImgDirFile(){

        // 构建上传文件的存放 "文件夹" 路径
        String fileDirPath = new String("src/main/resources/" + IMG_PATH_PREFIX);

        File fileDir = new File(fileDirPath);
        if(!fileDir.exists()){//是否存在目录或文件
            // 递归生成文件夹
            fileDir.mkdirs();
        }
        System.out.println(fileDir);
        return fileDir;
    }
   
    public static String getTime(){
        Date data=new Date();
        String getTime=""+data.getTime();
        return getTime;
    }
}

业务层 service

@Service("userLogonService")
 public class UserLogonServiceImpl implements UserLogonService {
 @Override
    public UserMsg UploadAvatar(MultipartFile imgFile,UserMsg userMsg) {
        String msg = "";
        if (imgFile.isEmpty()) {
            msg="未上传头像!";
        }else {
            // 拿到文件名
            String filename = imgFile.getOriginalFilename();//获取图片的文件名
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);//获取文件的后缀名
            filename=UploadUtils.getTime()+"."+suffix;//对图片的文件名称重新命名,防止重排
            userMsg.setAddress(filename);
            // 存放上传图片的文件夹
            File fileDir = UploadUtils.getImgDirFile();
            // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
            //  System.out.println(fileDir.getAbsolutePath());
            try {
                // 构建真实的文件路径
                File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
                // 上传图片到 -》 “绝对路径”
                imgFile.transferTo(newFile);
                msg = "头像上传成功!";
            } catch (IOException e) {
                msg = "头像上传失败!";
            }
        }
        userMsg.setImageMessage(msg);
        return userMsg;
    }
 }

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.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xxx</groupId>
    <artifactId>chatroom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>chatroom</name>
    <description>Demo project for Spring Boot</description>

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


    <dependencies>

        <!--核心依赖,包括auto-configuration , logging和YAML。-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--
        默认使用嵌入式的tomcat作为web容器对外提供HTTP服务。
        提供了很多以server.为前缀的配置项用于对嵌入式Web容器提供配置,比如:
        server.port,server.address,server.ssl.*,server.tomcat.*
        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--thymeleaf依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.3</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!--将Spring Boot应用打包为可执行的jar或war文件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件 application.properties

#端⼝
server.port=8080
#项⽬访问路径
#server.servlet.context-path=/springboot
##cookie失效时间
#server.servlet.session.cookie.max-age=100
##session失效时间
#server.servlet.session.timeout=100
#编码格式
server.tomcat.uri-encoding=UTF-8

#模版路径
spring.thymeleaf.prefix=classpath:/templates/
#模板后缀
spring.thymeleaf.suffix=.html
# 设置Content-type
spring.thymeleaf.servlet.content-type=text/html
# 设置编码方式
spring.thymeleaf.encoding=UTF-8
# 校验H5的格式
spring.thymeleaf.mode=HTML5
# 关闭缓存,在开发过程中可以立即看到页面修改效果
spring.thymeleaf.cache=false

# 用来加载静态资源的
spring.mvc.static-path-pattern=/static/**

# spring 链接数据库
#spring.datasource.url=jdbc:mysql://localhost:3306/db_chat?#useUnicode=true&characterEncoding=UTF-8
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.username=root
#spring.datasource.password=root
# mybatis
#mybatis.mapper-locations=classpath:/mapping/*.xml
#mybatis.type-aliases-package=com.xxx.entity

# 配置头像上传,图片保存的位置
#file-save-path=C:\chatroom\src\main\resources\static\image\
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值