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.
61 lines
2.1 KiB
61 lines
2.1 KiB
package com.example.controller;
|
|
|
|
import cn.hutool.core.io.FileUtil;
|
|
import com.example.common.Result;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
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;
|
|
|
|
@RestController
|
|
@RequestMapping("/files")
|
|
//上传
|
|
public class FileController {
|
|
|
|
@Value("${ip}")
|
|
private String ip;
|
|
|
|
@Value("${server.port}")
|
|
private String port;
|
|
|
|
private static final String ROOT_PATH =System.getProperty("user.dir")+"/files";
|
|
|
|
@PostMapping("/upload")
|
|
public Result upload(MultipartFile file) throws IOException {
|
|
String originalFilename=file.getOriginalFilename();//文件名
|
|
long flag=System.currentTimeMillis();
|
|
String fileName=flag+"_"+originalFilename;
|
|
|
|
File finalFile = new File(ROOT_PATH + "/" + fileName);
|
|
if (!finalFile.getParentFile().exists()){
|
|
finalFile.getParentFile().mkdirs();
|
|
}
|
|
file.transferTo(finalFile);
|
|
//返回url
|
|
|
|
String url ="http://" + ip +":" + port +"/files/download?fileName=" + fileName;
|
|
|
|
|
|
return Result.success(url);
|
|
}
|
|
@GetMapping("/download")
|
|
public void download(String fileName, HttpServletResponse response) throws IOException {
|
|
File file = new File(ROOT_PATH + "/" + fileName); // 文件在存盘存储的对象
|
|
ServletOutputStream os = response.getOutputStream();
|
|
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
|
|
response.setContentType("application/octet-stream");
|
|
// os.write(FileUtil.readBytes(file));
|
|
FileUtil.writeToStream(file, os);
|
|
os.flush();
|
|
os.close();
|
|
}
|
|
}
|