jeefast框架,自带拦截器,必须要在拦截器中开放设置图片路径的方法才可以正常访问,否则直接在浏览器地址栏输入图片的地址会报错 {“msg”:“invalid token”,“code”:500} 。
开放拦截器的位置(不好意思,因为弄了pom文件,导致项目报错了,但是暂时不影响使用)
红框中第二个文件是拦截器代码的位置,第一个是写设置图片目录代码的文件
这里除了红框中的代码,其它都是自带的。添加的时候一定要在指定的位置添加,不然就会报标题上的错误。
这个就是写设置图片位置的代码,学springboot的时候是在启动类中写的,现在就没必要在启动类里面写了,只要在这里面写就可以了。
图片上传的控制器代码
//处理文件上传
@ResponseBody //返回json数据
@RequestMapping(value = "upload", method = RequestMethod.POST)
public JSONObject uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
//String contentType = file.getContentType();
//System.out.print(contentType);//这里可以输出一下获取到的东西,我忘了能输出什么了
String fileName = "Nfnotice"+System.currentTimeMillis()+file.getOriginalFilename();//"Notice"是我的文件名,+根据当前时间命名+文件原名
String filePath = "E:/ExerciseSpace/SpringBoot/imageg";
//String imgPath = filePath+fileName;//文件的路径+文件名
//下面的代码就直接复制好了
JSONObject jo = new JSONObject();//实例化json数据
if (file.isEmpty()) {
jo.put("success", 0);
jo.put("fileName", "");
}
try {
uploadFile(file.getBytes(), filePath, fileName);
jo.put("success", 1);
jo.put("fileName", fileName);
// jo.put("xfileName", filePath+"/"+fileName);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
//返回json
return jo;
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
out.write(file);
out.flush();
out.close();
}
js代码
//这个方法就是为了隐藏那个很low的文件上传按钮准备的
dr: function(){
$("#file").click();
},
//图片上传
img:function(){
var form = new FormData();
form.append("file", document.getElementById("file").files[0]);
$.ajax({
url: baseURL + "platform/notice/upload", //后台url
data: form,
cache: false,
async: false,
type: "POST", //类型,POST或者GET
dataType: 'json', //数据返回类型,可以是xml、json等
processData: false,
contentType: false,
success: function (data) { //成功,回调函数
if (data) {
vm.imgpath = "/imctemp-rainy/"+data.fileName;
var pic="/jeefast" + vm.imgpath; //文件具体路径,这里具体要加什么,看你的链接名字,我访问的路径是localhost:8080/jeefast/*,所以要加一个jeefast才能正常访问
$("#url img").attr("src",pic);//将上传的图片进行前台展示
//alert("上传成功 "+vm.imgpath);
} else {
alert("失败");
}
},
error: function (er) { //失败,回调函数
alert(JSON.stringify(er));
}
});
},
html代码
<div class="form-group" style="height: 350px">
<div class="col-sm-2 control-label">图片上传:
<label class="radio-inline">
<a class="btn btn-primary btn-sm" v-on:click="dr()">
<i class="fa fa-plus"></i> 选择图片</a>
</label>
</div>
<label class="radio-inline">
<p id="url" style="border: 1px double;border-width:4px">
<img src="/jeefast/imctemp-rainy/no.jpg" width=200></p><!-- 这里是一个默认显示的图片地址,如果不显示的话,可以调用浏览器控制台,查看此处访问的真实地址,根据真实地址进行修改,修改成正确的地址,刚开始的时候我都是用../../imctemp—rainy/no.jpg才能访问的 -->
</label>
<input type="file" name="file" id="file" style="display:none" v-on:change="img"/>
</div>