SpringBoot文件上传

前端:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传title>
head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
form>
body>
html>

application.properties:

#上传的目标路径
file.path= D:/upload/

#上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB

#单个文件的最大值
spring.servlet.multipart.max-file-size=10MB

后端:

package com.cqf.infosystem.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@Controller
public class UploadController {

    @Value("${file.path}")
    private String filePath;

    @ResponseBody
    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }
        //获取上传文件的后缀名
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //判断上传文件类型,必须是jpg或是txt
        if (!(".jpg".equals(extName) || ".txt".equals(extName))){
            return "文件类型必须是jpg或txt!请重新上传";
        }
        //随机生成上传后的文件名
        String fileName = UUID.randomUUID().toString() + extName;
        //将上传的文件拷贝至目标路径下
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath + fileName)));
        //返回文件名
        return "上传成功,文件名为:" + fileName;
    }
}

你可能感兴趣的:(SpringBoot文件上传)