以前用PHP的时候上传图片直接放在项目文件夹下,浏览器输入地址就有了
用了JAVA发现这个不可行
目前主流的方法是
将图片存于特定的磁盘文件夹下,写一个带文件名参数的控制器,控制器将图片找出来并展示在网页中
这样就能实时预览图片
写一下图片文件上传 将文件上传到D:/webimg中 并返回地址
public String uploadImg(MultipartFile file) {
String type = null;
String path = null;
if(file == null){
return "{\n" +
" \"code\": 0\n" +
" ,\"msg\": \"无文件上传\"\n" +
" ,\"data\": {\n" +
" \"src\": \"\"\n" +
" }\n" +
"} ";
}
String fileName = file.getOriginalFilename();
// 判断文件类型
type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
if(type == null){
return "{\n" +
" \"code\": 0\n" +
" ,\"msg\": \"文件格式错误\"\n" +
" ,\"data\": {\n" +
" \"src\": \"\"\n" +
" }\n" +
"} ";
}else if(!type.equals("jpg") && !type.equals("png") && !type.equals("gif") && !type.equals("jpeg")){
return "{\n" +
" \"code\": 0\n" +
" ,\"msg\": \"文件格式错误\"\n" +
" ,\"data\": {\n" +
" \"src\": \"\"\n" +
" }\n" +
"} ";
}else{
String realPath = "D:\\webimg\\";
int randNum = (int)Math.random()*100;//随机数
String newfileName = String.valueOf(System.currentTimeMillis())+String.valueOf(randNum)+"."+type;
//图片名=时间戳+随机数
path = realPath+newfileName;
//真实的路径:文件夹+文件名
//System.out.println(path);
try {
file.transferTo(new File(path));
//返回一个控制器+文件名的地址
//如 /uploads/1111.jpg
return "{\n" +
" \"code\": 1\n" +
" ,\"msg\": \"上传成功\"\n" +
" ,\"data\": {\n" +
" \"src\": \"/uploads/"+newfileName+"\"\n" +
" }\n" +
"} ";
} catch (IOException e) {
e.printStackTrace();
}
}
return "{\n" +
" \"code\": 0\n" +
" ,\"msg\": \"未知错误\"\n" +
" ,\"data\": {\n" +
" \"src\": \"\"\n" +
" }\n" +
"} ";
}
浏览图片控制器(/uploads)
刚刚上传成功时,返回了一个地址 如:/uploads/111.jpg
把他拆分一下 /控制器/文件名
所以获取后面的文件名 在控制器中去找到这个文件 再转发到网页 就可以实现平常的实时预览
@RequestMapping("/uploads/{imgName}")
public void uploads(@PathVariable("imgName") String imgName, HttpServletResponse response){
String path = "D:\\webimg\\";//取图片的地址
String type=imgName.indexOf(".")!=-1?imgName.substring(imgName.lastIndexOf(".")+1, imgName.length()):null;//获取请求访问的文件类型
//System.out.println(type);
type = type.toLowerCase();//转换小写
//判断请求访问的文件类型
if(type == null){
try {
response.sendError(404);
} catch (IOException e) {
e.printStackTrace();
}
}else if (!type.equals("jpg") && !type.equals("png") && !type.equals("gif") && !type.equals("jpeg")){
try {
response.sendError(404);
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fis;
response.setContentType("image/"+type+";charset=UTF-8");
try {
fis = new FileInputStream(path+imgName);
int i = fis.available();
byte[] data = new byte[i];
fis.read(data);
fis.close();
//写图片到页面
OutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}