文件上传下载后端代码
- Upload 工具类:
@Component
@ConfigurationProperties("upload")
public class Upload {
private Logger log = LoggerFactory.getLogger(Upload.class);
// 获取存放位置
private Map<String, String> location;
// 单个文件大小
private String maxFileSize;
// 上次总文件大小
private String maxRequestSize;
// token验证密钥
private String secret;
public Map<String, String> getLocation() {
return location;
}
public void setLocation(Map<String, String> location) {
this.location = location;
}
public String getMaxFileSize() {
return maxFileSize;
}
public void setMaxFileSize(String maxFileSize) {
this.maxFileSize = maxFileSize;
}
public String getMaxRequestSize() {
return maxRequestSize;
}
public void setMaxRequestSize(String maxRequestSize) {
this.maxRequestSize = maxRequestSize;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getBasePath() {
String location = "";
//system.getProperty获取系统属性名称
String os = System.getProperty("os.name");
//系统属性名称是否是以win为前缀
if(os.toLowerCase().startsWith("win")) {
location = this.getLocation().get("windows");
} else {
location = this.getLocation().get("linux");
}
return location;
}
/**
* @Description: TODO(初始化文件上传)
* @param
* @throws
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 设置文件大小限制 ,超出设置页面会抛出异常信息,
// 这样在文件上传的地方就需要进行异常信息的处理了;
factory.setMaxFileSize(this.getMaxFileSize()); // KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize(this.getMaxRequestSize());
// Sets the directory location where files will be stored.
// factory.setLocation(this.getBasePath());
log.info("初始化上传参数成功。");
return factory.createMultipartConfig();
}
}
- 文件上传工具类
public class FilesUpload {
private static final Logger log = LoggerFactory.getLogger(FilesUpload.class);
private static FilesUpload filesUpload = null;
private FilesUpload() {
}
public static FilesUpload getIntance() {
if (filesUpload == null) {
filesUpload = new FilesUpload();
}
return filesUpload;
}
/**
* @Description: TODO(存储)
* @param file
* @param path
* @throws Exception
*/
public boolean saveFile(MultipartFile file, String path) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
File saveDir = new File(path);
if (!saveDir.getParentFile().exists())
saveDir.getParentFile().mkdirs();
// 转存文件
file.transferTo(saveDir);
return true;
// return list;
} catch (Exception e) {
e.printStackTrace();
log.error("存储pdf异常,数据详情 --> | " + JSON.toJSONString(file) + " | 异常信息 --> |"+e.getMessage());
}
}
return false;
}
}
- 文件下载工具类
public class DownloadUtil {
/**
* 获取源文件物理路径
* @param realPath
* @return
*/
public static String getPath(String realPath){
if(realPath!=null&&realPath.length()>0){
String[] pa = realPath.split("/");
String path = "";
//获取文件保存的物理路径
for (int i = 0; i < pa.length - 1; i++) {
if (i >= 0 && i == pa.length - 2) {
path = path + pa[i];
} else {
path = path + pa[i] + "/";
}
}
return path;
}else{
return null;
}
}
public static void downFile(HttpServletResponse response,File file,String vcName){
boolean bo=file.exists();
if (bo) {
try {
//把文件名按UTF-8取出并按ISO8859-1编码,保证弹出窗口中的文件名中文不乱码,中文不要太多,最多支持17个中文,因为header有150个字节限制。
vcName = new String(vcName.getBytes("UTF-8"), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/force-download");// 设置强制下载不打开
//response.setContentType("application/octet-stream");// 告诉浏览器输出内容为流
//Content-Disposition中指定的类型是文件的扩展名,并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的,点保存后,
// 文件以filename的值命名,保存类型以Content中设置的为准。注意:在设置Content-Disposition头字段之前,一定要设置Content-Type头字段。
response.addHeader("Content-Disposition", "attachment;fileName=" + vcName);// 设置文件名
String len = String.valueOf(file.length());
response.setHeader("Content-Length", len);//设置内容长度
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
// System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
- controller层
@Controller
@RequestMapping("/upkeep")
public class UpkeepController{
@Resource
Upload upload;
@PostMapping(value = "/addSl", name = "上传文件")
@ResponseBody
public ResultMsg addSl(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
SavePdf sp = new SavePdf();
//获取文件名称
String fileName = file.getOriginalFilename();
UpkeepSpecial entity = new UpkeepSpecial();
String uuid = UUIDUtil.uuid();
//设置主键ID
entity.setVcId(UUIDUtil.uuid());
//对象设置标题
entity.setVcName(fileName);
//设置唯一文件名称vcInPath
String name = sp.getPdfName(uuid, fileName);
entity.setVcInPath(name);
//设置唯一文件保存物理路径
String path = upload.getBasePath() + name;
entity.setVcOutPath(path);//附件保存的物理路径
FilesUpload.getIntance().saveFile(file, path);
ResultMsg resultMsg = upkeepService.addSl(entity);
return resultMsg;
}
@RequestMapping(value = "/downloadSl", name = "下载")
public void downloadFileSl(HttpServletRequest request, HttpServletResponse response, String vcId) {
//获取entity对象
UpkeepSpecial entity = upkeepService.infoSl(vcId);
String fileName = entity.getVcInPath();//设置文件名,根据业务需要替换成要下载的文件名
String vcName = entity.getVcName();
//通过物理路径上传文件
String realPath = entity.getVcOutPath();
File file = new File(realPath);
DownloadUtil.downFile(response, file, vcName);
}
}