这里记录一个java后台比较常见的功能,文件上传与下载,以及返回图片直接用于游览器展示或者标签展示。
这里的文件上传主要是通过from表单指定提交类型为multipart/form-data,然后利用springboot(springmvc也一样但springmvc需要导入几个文件上传相关包)的multipartFile类直接接收。multipartFile类接收后利用这个类的api获取文件信息以及输入流进行你需要的操作。下面给出前后端代码
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file){
if (file == null || file.isEmpty()){
return "file is null";
}
String filename = file.getOriginalFilename();
String path = "D:/" + "lhp_" + StringUtil.formateFileName(filename);
File newFile = new File(path);
try {
file.transferTo(newFile);
} catch (IOException e) {
return e.toString();
}
return "upload success";
}
//格式化文件名的工具类
public class StringUtil {
// ie游览器提交文件名会包含路径在类,去掉路径
public static String formateFileName(String originFileName) {
if (originFileName == null || originFileName.length() <= 0) {
return "";
}
// unix系统路径以'/'分隔
int unixSep = originFileName.lastIndexOf("/");
// windows系统路径以'\'分隔
int winSep = originFileName.lastIndexOf("\\");
int po = winSep > unixSep ? winSep : unixSep;
po++;//从'\'的下一个开始字符截取
return originFileName.substring(po);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传</title>
</head>
<body>
<form enctype="multipart/form-data" action="http://localhost:8080/upload" method="POST">
<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
文件下载只要把文件内容以写入到response的输出流中,最后指定response的header中的Content-Disposition为attachment,也就是告诉游览器你是要下载它而不是解析它。
@RequestMapping("/download")
@ResponseBody
public String download(HttpServletResponse response, @RequestParam("filename") String filename){
File file = new File("D:\\lhp_" + filename);
if (!file.exists()) {
return "file not exist";
}
try {
//这行代码主要用于解决文件名为中文是,下载显示文件名乱码
filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.reset();
response.setHeader("Content-Disposition", "attachment;fileName=\"" + filename + "\"");
try {
InputStream inStream = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = inStream.read(buff)) > 0) {
os.write(buff, 0, len);
}
os.flush();
os.close();
inStream.close();
} catch (Exception e) {
e.printStackTrace();
return "装换成输出流出错";
}
return "正在下载";
}
图片展示其实就可以利用上面的文件下载,不指定Content-Disposition,游览器就会自己解析它,甚至你都不用设置response的contentType为imag,游览器也能解析它,这里再给出一种方法,就是把图片读到一个byte数组中,然后返回这个数组,springboot会帮我们把这个byte数组写入到请求体。equestMapping中指定produces为image就相当于response的contenttype的指定为image一样。
@RequestMapping(value = "/showimage",
produces = {MediaType.IMAGE_JPEG_VALUE,
MediaType.IMAGE_PNG_VALUE,
MediaType.IMAGE_GIF_VALUE})
@ResponseBody
public byte[] showImage(HttpServletResponse response, @RequestParam("filename") String filename) {
File file = new File("D:\\lhp_" + filename);
FileInputStream inputStream = null;
byte[] bytes = null;
try {
inputStream = new FileInputStream(file);
bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
} catch (IOException e) {
e.printStackTrace();
//可以设置显示一个出错的图片
}
return bytes;
}