import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hk.sky.bean.Admin;
import com.hk.sky.bean.ImgFile;
import com.hk.sky.common.Result;
import com.hk.sky.service.ImgFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("/imgFile")
public class FileController {
@Value("${saveImg.upload.path}")
private String uploadPath;
@Autowired
ImgFileService imgFileService;
//文件上传
@PostMapping("/upload")
public Result upload(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
String type = FileUtil.extName(originalFilename);
long size=multipartFile.getSize();
//定义一个文件的唯一标识
String uuid= IdUtil.fastSimpleUUID();
String fileUUID=uuid+ StrUtil.DOT+type;
//判断文件的放置路径是否存在
File fileUpload = new File(uploadPath + fileUUID);
File parentPath=fileUpload.getParentFile();
if(!parentPath.exists()){
parentPath.mkdirs();
}
String url;
//把获取的文件存储到磁盘目录
multipartFile.transferTo(fileUpload);
url="http://localhost:8090/imgFile/"+fileUUID;
return Result.Success(url);
}
//文件下载
@GetMapping("/{fileUUID}")
public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
File uploadFile=new File(uploadPath+fileUUID);
ServletOutputStream os=response.getOutputStream();
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
response.setContentType("application/octet-stream");
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}
文件上传与下载
最新推荐文章于 2024-10-31 18:26:46 发布