配置
tupian:
uploadPath: d:/file
url: http://192.168.8.69:${server.port}/files/
//文件映射类
@Component
@ConfigurationProperties(prefix = "图片")
public class StaticFile {
private String uploadPath;
private String url;
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
//项目路径配置
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Autowired
private StaticFile staticFile;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("file:///"+staticFile.getUploadPath()+"/");
}
}
//文件上传代码
import org.springframework.util.Base64Utils;//base64转换工具类
import org.apache.commons.io.FileUtils;//文件IO工具类
@Override
public ResultBean fileUpLoad(String fileBase64) {
String dataPrix = "";
String data = "";
String suffix = "";
if (StringUtils.isEmpty(fileBase64)){
return new ResultBean(500,"缺少必要参数");
}else {
String[] d = fileBase64.split("base64,");
if(d != null && d.length == 2){
dataPrix = d[0];
data = d[1];
}else{
return new ResultBean(500,"base64参数不合法");
}
}
if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){
//data:image/jpeg;base64,base64编码的jpeg图片数据
suffix = ".jpg";
} else if("data:image/png;".equalsIgnoreCase(dataPrix)){
//data:image/png;base64,base64编码的png图片数据
suffix = ".png";
}else if ("data:application/vnd.ms-excel;".equals(dataPrix)){
suffix = ".xls";
}else if ("data:application/msword;".equals(dataPrix)){
suffix = ".doc";
}else if ("data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;".equals(dataPrix)){
suffix = ".docx";
}else if ("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;".equals(dataPrix)){
suffix = ".xlsx";
}else{
return new ResultBean(500,"文件只支持[.jpg,.png,.xls,.doc,.docx,.xlsx]格式的文件");
}
String uuid = UUIDUtils.getUUID();
String fileName = uuid+suffix;
try {
String nowDate = DateUtils.getCurrentDate("yyyy-MM-dd");
byte[] bs = Base64Utils.decodeFromString(data);
FileUtils.writeByteArrayToFile(new File(staticFile.getUploadPath()+"/"+nowDate, fileName), bs);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("fileUrl",pathFileName);
return new ResultBean(200,"文件接收成
}catch (Exception e){
e.printStackTrace();
return new ResultBean(500,"文件接收失败");
}
}