本篇文章给大家分享的是有关怎么在Spring Boot中利用ajax上传图片,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
1.启动类中加入
SpringBoot重写addResourceHandlers映射文件路径
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/");
}
设置静态资源路径
2. 表单 前端 页面
<input type="file" name="file" id="file">
<p id="url"><img src="" width=200></p>
<input type="button" id="button" value="上传" >
$(function () {
$("#button").click(function () {
var form = new FormData();
form.append("file", document.getElementById("file").files[0]);
$.ajax({
url: "/stu/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) {
var pic="/imctemp-rainy/"+data.fileName;
$("#url img").attr("src",pic);
// alert(JSON.stringify(data));
} else {
alert("失败");
}
},
error: function (er) { //失败,回调函数
alert(JSON.stringify(data));
}
});
})
})
控制器
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();
}
//处理文件上传
@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 = System.currentTimeMillis()+file.getOriginalFilename();
String filePath = "D:/E";
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
}
//返回json
return jo;
}
以上就是怎么在Spring Boot中利用ajax上传图片,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.jb51.net/article/174084.htm