1.创建SpringBoot项目,并在application.properties中增加相关配置:
server.port=8093
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
fileDirectory=d:\\3322\\
2.定义文件上传的controller
package cn.edu.tju.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@CrossOrigin
@RestController
public class UploadController {
//文件的保存目录,从application.properties中获取
@Value("${fileDirectory}")
private String fileDirectory;
//需要前端发送的post请求的参数名为 file
@RequestMapping("/fileUpload")
public String fileUpload(MultipartFile file) throws Exception{
try{
//获取文件名
String fileName=file.getOriginalFilename();
//拼接完整的文件保存路径
String fileFullPath=fileDirectory+fileName;
//删除现有的同名文件(如果有)。如果直接调用delete方法,会抛异常
Files.deleteIfExists(Paths.get(fileFullPath));
//保存文件
file.transferTo(new File(fileFullPath));
} catch (Exception ex){
System.out.println(ex.getMessage());
return ex.getMessage();
}
return "文件上传成功.";
}
}
3.定义启动类并启动程序
启动类:
package cn.edu.tju;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Start {
public static void main(String[] args) {
SpringApplication.run(Start.class,args);
}
}
- elment-ui 文件上传组件
<el-upload
class="upload-demo"
name="file"
action="http://localhost:8093/fileUpload/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="10"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
|