一、快速入门
-application.yml配置上传的路径
reggie:
path: C:\Users\Pipiktd\Pictures\
- controller
package com.ylf.controller;
import com.ylf.common.CustomException;
import com.ylf.common.Result;
import lombok.extern.slf4j.Slf4j;
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.FileInputStream;
import java.io.IOException;
import java.util.UUID;
/**
* @author ylf
* @version 1.0
*/
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@Value("${reggie.path}")
private String path;
@PostMapping("/upload")
/** MultipartFile是spring提供的类,file必须和前端input的name值对应 */
public Result<String> upload(MultipartFile file) {
log.info(file.toString());
// 获取原始文件名
final String originalFilename = file.getOriginalFilename();
final String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 使用uuid拼接组成文件名
String fileName = UUID.randomUUID().toString() + suffix;
try {
file.transferTo(new File(path + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return Result.success(fileName);
}
@GetMapping("/download")
public void download(String name, HttpServletResponse response) {
try {
final FileInputStream fileInputStream = new FileInputStream(new File(path + name));
final ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
int len = 0;
final byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
throw new CustomException("文件不存在");
}
}
}
网友评论