例子点这里:https://blog.csdn.net/qq_38262266/article/details/81020328
例子点这里:https://www.cnblogs.com/xQlover/p/9898255.html
路径问题:https://blog.csdn.net/qq_20597149/article/details/79872579
配置视图解析器
<!-- 配置文件上传视图解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
jsp layui框架
<div class="layui-upload">
<label for="username" class="layui-form-label">
<span class="x-red">*</span>图片</label>
<div class="layui-input-inline">
<button type="button" class="layui-btn" id="test1">上传图片</button>
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1" width="100px" height="100px">
<p id="demoText"></p>
</div>
</div>
</div>
js
$ = layui.jquery;
var form = layui.form,
upload = layui.upload,
layer = layui.layer;
//普通图片上传
var uploadInst = upload.render({
elem: '#test1'
,url: '<%=basePath%>/admindish/image'
,before: function(obj){
//预读本地文件示例,不支持ie8
obj.preview(function(index, file, result){
$('#demo1').attr('src', result); //图片链接(base64)
});
}
,done: function(res){
//如果上传失败
if(res.code > 0){
return layer.msg('上传失败');
}
//上传成功
}
,error: function(){
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function(){
uploadInst.upload();
});
}
});
后台
@RequestMapping(value = "/image", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> image(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request, HttpServletResponse response)
{
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map = new HashMap<String, Object>();
String filename = "";
String localPath = "D:\\imgs\\";
try {
if (file != null) {
//生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//获得文件类型(可以判断如果不是图片,禁止上传)
String contentType = file.getContentType();
//获得文件后缀名
String suffixName = contentType.substring(contentType.indexOf("/") + 1);
//得到 文件名(随机数+uuid+后缀)
filename = (int)((Math.random())*100000000)+uuid + "." + suffixName;
// 判断是否有这个文件夹,没有就创建
if (!new File(localPath).exists()) {
new File(localPath).mkdirs();
}
// 复制到当前文件夹
file.transferTo(new File(localPath + filename));
}
} catch (Exception e) {
map.put("code", 1);
map.put("msg", "");
map.put("data", map2);
map2.put("src", filename);
System.out.println("上传失败");
return map;
}
map.put("code", 0);
map.put("msg", "");
map.put("data", map2);
map2.put("src", filename);
System.out.println("上传成功");
return map;
}
网友评论