application.yml配置文件上传路径
#文件存储路径
filepath:
sourcePath: /data/img/
图片上传预览controller
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
@Api(tags = "图片上传接口")
@RestController
@RequestMapping("/api/file")
@Slf4j
public class FileController {
@Value("${filepath.sourcePath}")
private String filepath;
/**
* 处理文件上传
*/
@PostMapping(value = "/upload")
public String uploading(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
String filePath = filepath; // 上传后的路径
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
/**
* 返回前端图片输出流数据
* @param response
* @param imgId 图片名称加后缀
* @return
* @throws Exception
*/
@ApiOperation("返回前端图片输出流数据")
@GetMapping(value = "/image",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public byte[] getImage(HttpServletResponse response,@ApiParam("图片名称+后缀格式") String imgId) throws Exception {
File file = new File(filepath + imgId);
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
}
上传图片调用upload方法,成功后返回图片名称。
显示图片调image接口传入图片名称。
|