在实际开发中我们经常要上传文件或者一些图片什么的,那么spingboot如何来处理这些情况呢?这一篇我将模拟简单的图片,文档上传的功能的demo
1。添加一个简单的html页面(picUpload.html)
<!DOCTYPE HTML>
<html>
<head>
<title>pictureUploading</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8 ">
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="fileUpload"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
2.写一个controller作为跳转(HtmlController)
package com.yian.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HtmlController {
@RequestMapping("/picUpload")
public String picUpload(){
return "picUpload";
}
}
3。在写一个controller作为文件上传后的逻辑处理(UploadController)
package com.yian.springboot.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.yian.springboot.util.FileUtil;
import com.yian.springboot.vo.Message;
@RestController
public class UploadController {
@PostMapping("/upload")
public Object upload(MultipartFile fileUpload) throws IOException{
//获取文件名
String fileName = fileUpload.getOriginalFilename();
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的文件是"+suffixName);
//重新生成文件名
fileName = UUID.randomUUID()+suffixName;
//指定本地文件夹存储图片
String filePath = "E:/project/springBoot/src/main/resources/static/";
//指定上传文件的绝对路径
String fileed=filePath+"/"+fileName;
try {
//将图片保存到static文件夹里
fileUpload.transferTo(new File(filePath+fileName));
if(".txt".equals(suffixName)){
//文件编码
String Filestr = FileUtil.resolveCode(fileed);
//文件内容
String FileString = FileUtil.readTxt(fileed);
System.out.println(Filestr+"---------");
System.out.println(FileString+"++++++++");
return new Message(0,"上传成功", "文件内容为"+FileString);
}else{
return new Message(-1,"上传成功","文件不是以.txt结尾的");
}
}catch (Exception e){
e.printStackTrace();
return new Message(0,"上传失败","上传的此文件是以.txt结尾的");
}
}
}
4.解析文件的工具
package com.yian.springboot.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class FileUtil{
/**
* 解析普通文本文件 流式文件 如txt
* @param path
* @return
*/
public static String readTxt(String path){
StringBuilder content = new StringBuilder("");
try {
String code = resolveCode(path);
File file = new File(path);
InputStream is = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(is, code);
BufferedReader br = new BufferedReader(isr);
// char[] buf = new char[1024];
// int i = br.read(buf);
// String s= new String(buf);
// System.out.println(s);
String str = "";
while (null != (str = br.readLine())) {
content.append(str);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("读取文件:" + path + "失败!");
}
return content.toString();
}
/**
* 读取文件编码
* @Title: resolveCode
* @Description: TODO
* @param path
* @return
* @throws Exception
* @author chengshengqing-YiAn 2019年3月1日 下午1:52:05
*/
public static String resolveCode(String path) throws Exception {
InputStream inputStream = new FileInputStream(path);
byte[] head = new byte[3];
inputStream.read(head);
String code = "gb2312"; //或GBK
if (head[0] == -1 && head[1] == -2 )
code = "UTF-16";
else if (head[0] == -2 && head[1] == -1 )
code = "Unicode";
else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
code = "UTF-8";
inputStream.close();
//System.out.println(code);
return code;
}
}
5。最后访问 http://localhost:8080/picUpload 上传文件
6。最后刷新工程就会出现我们上传的文件了
注意:
1。 上面的工具类针对我们上传的txt文件结尾的可能会因为编码的不同引起上传之后打开里面的内容发现乱码,那是因为我们上传文件的编码和我们工程中设置的编码格式不一致导致,我的工具类里面针对此问题,有专门解析此内容的,可以通过此工具类来获取到上传的文件内容。
2。因为我的工具类是针对简单的txt文件,所以我在上面的代码中做了判断,如果上传的不是txt结尾的文本,暂且我没有支持。
工程结构图:
参考书籍:柳伟卫编著的书籍《SpringCloud微服务架构开发实战》