You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
3.2 KiB

package com.xin.lcyxjy.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.xin.lcyxjy.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/files")
public class FileController {
private static final String filePath = System.getProperty("user.dir") + "/files/";
@Value("9999")
private String port;
@Value("localhost")
private String ip;
/**
* 单文件上传
*
* @param file
* @return
*/
@PostMapping("/upload")
public Result upload(MultipartFile file) throws InterruptedException {
String flag;
synchronized (FileController.class) {
String filePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
flag = System.currentTimeMillis() + "";
Thread.sleep(1L);
}
Thread.sleep(1000);
String fileName = file.getOriginalFilename();
try {
if(!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
System.out.println(fileName + "--上传成功");
} catch (Exception e) {
System.err.println(fileName + "--文件上传失败");
}
String http="http://"+ip+":"+port+"/files/";
return Result.success(http+flag+"-"+fileName);
}
/**
* 获取文件
*
* @param flag
* @param response
*/
@GetMapping("/{flag}")
public void avatarPath(@PathVariable String flag, HttpServletResponse response)
{
if(!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
OutputStream os;
// String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
try {
if (StrUtil.isNotEmpty(flag)) {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
response.setContentType("application/octet-stream");
byte[] bytes = FileUtil.readBytes(filePath + flag);
os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("文件下载失败");
}
}
/**
* 删除文件
*
* @param flag
*/
@DeleteMapping("/{flag}")
public void delFile(@PathVariable String flag) {
List<String> fileNames = FileUtil.listFileNames(filePath);
if(!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
String filename = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
FileUtil.del(filePath + filename);
System.out.println("删除文件" + filename + "成功");
}
}