1、此前我们文章已经介绍过了关于Excel文件的上传和下载,这里的图片类似于之前的导入和导出,这里我们实战看一下吧!
2、文件上传接口编码
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@RestController
public class TestController {
protected final Logger logger = LoggerFactory.getLogger(getClass());
// 图片上传的类型
private String[] fileTypes = new String[] { "jpg", "gif", "bmp", "png", "jpeg", "JPG", "GIF", "BMP", "PNG", "JPEG",
"ico", "ICO" };
// 文件上传的类型
private String[] fileTypeArr = new String[] { "txt", "docx", "doc", "xlsx", "xls", "pdf", "rar", "zip", "jpg",
"ppt", "pptx", "wps", "gif", "bmp", "png", "jpeg", "TXT", "DOCX", "DOC", "XLSX", "XLS", "PDF", "RAR", "ZIP",
"JPG", "PPTX", "GIF", "BMP", "PPT", "WPS", "PNG", "JPEG" };
/**
* 文件上传接口 (单文件上传)
* @param flag 0 图片上传 1文件上传
*/
@ApiOperation(value = "文件上传接口", notes = "0 图片上传 1文件上传")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(MultipartFile file, @RequestParam String flag) {
logger.info("上传入参flag:" + flag);
long startTime = System.currentTimeMillis();
logger.info("文件开始上传");
List<Map<String, Object>> mapPath = new ArrayList<>();
// 上传文件名
String fileName = null;
// 文件后缀名
String fileSuffix = null;
// 文件大小
long size = 0;
// 文件上传时间
String upLoadTime = null;
// 将文件转字节数组需要
InputStream is = null;
// 打印上传文件文件信息
System.out.println("file:" + JSON.toJSONString(file));
// 取得当前上传文件的文件名称和后缀名
fileName = file.getOriginalFilename();
System.out.println("fileName:" + JSON.toJSONString(fileName));
fileSuffix = FilenameUtils.getExtension(fileName);
System.out.println("fileSuffix:" + JSON.toJSONString(fileSuffix));
// 0 图片上传 1文件上传
if ("0".equals(flag)) {
// 校验上传图片文件是否为规定的图片格式
if (Arrays.asList(fileTypes).contains(fileSuffix)) {
try {
if (file.getBytes() != null) {
is = new ByteArrayInputStream(file.getBytes());
size = (long) file.getSize();
upLoadTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
// 记录数据库或者上传fastdfs
....
} else {
try {
size = (long) file.getSize();
upLoadTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
// 记录数据库或者上传fastdfs
....
} catch (Exception e) {
logger.info("文件上传失败", e);
return "文件上传失败";
}
}
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败";
}
long endTime = System.currentTimeMillis();
logger.info("上传文件完成,耗时{}ms", endTime - startTime);
Map<String, Object> map = new HashMap<>();
map.put("fileName", fileName);
map.put("size", size);
map.put("upLoadTime", upLoadTime);
// 添加数据库保存的信息或者上传fastdfs的保存信息,使得前端可以获取
mapPath.add(map);
}
} else if ("1".equals(flag)) {
if (Arrays.asList(fileTypeArr).contains(fileSuffix)) {
try {
if (file.getBytes() != null) {
is = new ByteArrayInputStream(file.getBytes());
size = (long) file.getSize();
upLoadTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
// 记录数据库或者上传fastdfs
....
} else {
size = (long) file.getSize();
upLoadTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
// 记录数据库或者上传fastdfs
....
}
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败";
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 文件地址
Map<String, Object> map = new HashMap<>();
map.put("fileName", fileName);
map.put("size", size);
map.put("upLoadTime", upLoadTime);
// 添加数据库保存的信息或者上传fastdfs的保存信息,使得前端可以获取
mapPath.add(map);
}
}
if (mapPath.size() > 0) {
long endTime = System.currentTimeMillis();
logger.info("上传文件完成..........,耗时{}ms", endTime - startTime);
return JSON.toJSONString(mapPath);
}
return "文件上传失败";
}
}
3、文件获取接口
/**
* @param url
* @param response
*/
@ApiOperation("获取图片流")
@ApiImplicitParam(name = "url", value = "图片标识", dataType = "String", required = false, paramType = "query")
@RequestMapping(value = "writePic",method = RequestMethod.GET)
public void writePic(String url, HttpServletResponse response) {
OutputStream outputStream = null;
try {
// 这里我们模拟图片的字节流,实际中我们需要通过fastdfs或者数据库根据入参图片标识获取
File file = new File("E:\\0.jpg");
byte[] fileData = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
fileData = bos.toByteArray();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
// 写明要下载的文件的大小,设置输出类型和输出内容
if (fileData != null) {
response.setContentLength(fileData.length);
response.setHeader("Content-Disposition", "attachment;filename=" + url);
response.setContentType("image/jpeg");
outputStream = response.getOutputStream();
outputStream.write(fileData);
outputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
logger.error(null, e);
}
}
}
}
4、接口验证
上传接口
获取图片接口
5、本文中主要以图片为例,实际中,我们需要先上传保存文件信息,在预览文件信息,根据需求可以综合以上一个接口实现。
最后:以上仅为个人学习理解,学海无涯苦作舟,见一个学一个吧!