package zero.file.videoProject.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
@RequestMapping("/fullText")
@RestController
public class FullTextController {
private static final String STORE_DIR = "D:\\project\\零一电科\\技术资料\\lingyidianke\\zeroBackEnd\\ZerosBackEnd\\src\\main\\resources\\pict\\";
private static final String DOMAIN = "http://localhost:9090/fullText/file/download/";
static class Success {
public final int errno;
public final Object data;
public Success(String url) {
this.errno = 0;
HashMap<String, String> map = new HashMap<>();
map.put("url", url);
this.data = map;
}
}
@RequestMapping("/file/upload")
public Object uploadPict(@RequestParam("image") MultipartFile file) throws IOException {
// 获取文件流
// 获取文件真实名字
String fileName = UUID.randomUUID().toString().substring(0, 10) + file.getOriginalFilename();
// 在服务器中存储文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(STORE_DIR + fileName));
// 返回图片url
String url = DOMAIN + fileName;
return new Success(url);
}
@GetMapping("/file/download/{fileName}")
public void download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
// 获取真实的文件路径
String filePath = STORE_DIR + fileName;
System.out.println("++++完整路径为:"+filePath);
try {
// 下载文件
// 设置响应头
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
// 读取文件内容并写入输出流
Files.copy(Paths.get(filePath), response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
response.setStatus(404);
}
}
}