package com.xzhisoft.util;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileUpload {
/*文件上传
* 整成一个通用。
*
* 1.字节流的方式。write
* 2.使用transferTo springboot内部的转移文件的方法。
* */
public String fileUpload(MultipartFile files_param) throws Exception {
String file_name = files_param.getOriginalFilename();
Date date_param = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String number_result = simpleDateFormat.format(date_param);
String newName =number_result+"_"+ file_name;
//target文件夹中创建了
String paths = ResourceUtils.getFile("classpath:static").getPath() ;
String paths2=paths+ "/Files";
//"src"+File.separator+"main"+File.separator+"resources"+File.separator+"static"+File.separator+"Files";
File dir_file = new File(paths2);
if (!dir_file.exists()) {
dir_file.mkdirs();
}
File fileTransferTo = new File(dir_file, newName);
OutputStream outputStream = new FileOutputStream(fileTransferTo);
byte[] bytes = files_param.getBytes();
outputStream.write(bytes);
outputStream.close();
String url_result = "/Files/"+ newName;
return url_result;
}
}
https://blog.csdn.net/heylun/article/details/78732451
文件上传,获取当前项目的根路径。
本机//在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
//在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/