文件上传不用说了,很常用的一个功能。
application.yml
server:
port: 8001
servlet:
context-path: /
multipart:
#location:
#上传文件最大为
max-file-size: 10MB
#上传请求最大为
max-request-size: 20MB
#nio的web服务配置
undertow:
#为工作者创建的I/O线程数
io-threads: 20
#工作者线程数量
worker-threads: 50
#访问日志
accesslog:
enabled: false
# 文件上传配置
file:
enable: true
ip: 127.0.0.1
文件上传控制配置类FileConfig.java
package com.study.config;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import lombok.Data;
@Data
@Configuration
public class FileConfig {
@Value("${file.ip}")
private String ip;
@Value("${server.port}")
private Integer port;
@Value("${file.enable}")
private boolean enable;
public String getUrlString(boolean https) {
if (!enable) {
try {
InetAddress address;
address = InetAddress.getLocalHost();
ip = address.getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return https ? "https://" : "http://" + ip + ":" + port + "/";
}
public String getFileString(boolean https) {
return getUrlString(https) + "file/";
}
}
文件上传前端控制器FileController.java:
package com.study.system.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.study.config.FileConfig;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
@Resource
FileConfig fileConfig;
@PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
public String upload(MultipartFile file) throws IOException {
if (file.isEmpty()) {
return "请选择文件!";
}
String fileName = file.getOriginalFilename();
// 获取根目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) {
path = new File("");
}
File upload = new File(path.getAbsolutePath(), "static/file/");
if (!upload.exists()) {
upload.mkdirs();
}
String filePath = upload + "/" + fileName;
File localFile = new File(filePath);
FileOutputStream out = new FileOutputStream(localFile);
localFile.createNewFile();
out.write(file.getBytes());
log.info(localFile.getAbsolutePath());
out.flush();
out.close();
return fileConfig.getFileString(false) + fileName;
}
}
完结…