java 上传图片,图片预览,2种方法
1. 方法一:将图片上传到特定磁盘
html页面,form表单内容:
<div class="layui-form-item">
<label class="layui-form-label">头像</label>
<div class="layui-input-inline">
<input th:if="${bean!=null}" type="text" id="imagePath" name="photo" th:value="${bean.photo}" lay-verify="required" placeholder="请上传图片" autocomplete="off" class="layui-input dragImg" >
</div>
<button style="float: left;" type="button" class="layui-btn dragImg" id="layuiadmin-upload-useradmin">上传图片</button>
</div>
<div th:if="${bean==null}" class="layui-form-item" style="display: none" id="demo2">
<div class="layui-inline">
<label class="layui-form-label">预览效果:</label>
<img class="layui-upload-img" id="image" style="width: 9em;height: 9em">
</div>
</div>
<div class="layui-form-item layui-hide">
<input type="button" lay-submit lay-filter="LAY-user-back-submit" id="LAY-user-back-submit" value="确认">
</div>
layui -js代码:
layui.use(['index', 'form', 'user'], function(){
var $ = layui.$
,form = layui.form
,upload = layui.upload ;
// 上传头像
upload.render({
elem: '.dragImg' // 拖拽上传
,url: "/user/uploadPhoto"
,accept: 'images'
,method: 'post'
,acceptMime: 'image/*' // 图片类型
// ,ext: 'jpg|png|gif|bmp|jpeg'
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#image').attr('src', result); //图片链接(base64)
$('#demo2').show();
});
}
,done: function(res){
if(res.code==200){
let src = res.src; //把图片路径返回过来
$("#image").attr("src",src); //图片在预览上显示
$("#imagePath").attr("value",src); //给图片路径隐藏域赋值
}
// $(this.item).prev("div").children("input").val(res.src)
}
});
})
表单提交:
,yes: function(index, layero){
var iframeWindow = window['layui-layer-iframe'+ index]
,submitID = 'LAY-user-back-submit'
,submit = layero.find('iframe').contents().find('#'+ submitID);
//监听提交
iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
var field = data.field; //获取提交的字段
console.log(field.isUse)
//data.field里面的值为form要提交的数据
$.post("/user/admin/adminAdd",field,function(result){
if(result.code == 200){
layer.alert(result.msg,{icon:1,time: 1000});
//提交 Ajax 成功后,静态更新表格中的数据
table.reload('LAY-user-back-manage'); //数据刷新
layer.close(index); //关闭弹层
}else{
layer.alert(result.msg,{icon:2,time: 1000});
}
},"json");
});
submit.trigger('click');
}
control业务层:
/**
* 上传头像
*/
@Value("${file.uploadPath}")
private String basepath;
@RequestMapping(value = "/uploadPhoto", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json;charset=utf-8")
@ResponseBody
public Map<String, Object> uploadPhoto(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String uploadPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/";
// UploadUtil是一个工具类,返回的是图片的存储路径
String imagePath = UploadUtil.upload(file, basepath, uploadPath);
System.out.println(imagePath);
if (imagePath != null) {
map.put("code", 200);
map.put("msg", "上传成功");
map.put("src", imagePath);
} else {
map.put("code", 400);
map.put("msg", "上传失败");
}
return map;
}
添加UploadUtil工具类:
public class UploadUtil {
/**
*
* @param file
* @param basepath 定义一个上传文件的路径
* @param savepath 定义文件服务器的访问地址 images 目录要一致
* @return
*/
public static String upload(MultipartFile file,String basepath,String savepath){
//获得上传文件的名称
String filename = file.getOriginalFilename();
//创建UUID,用来保持文件名字的唯一性
String uuid = UUID.randomUUID().toString().replace("-","");
//进行文件名称的拼接
String newFileName = uuid+filename;
//创建文件实例对象
File uploadFile = new File(basepath,newFileName);
// 判断路径是否存在,没有创建
if (!uploadFile.getParentFile().exists()) {
uploadFile.getParentFile().mkdirs();
}
//执行文件上传的命令
try {
//图片存进目录下去
file.transferTo(uploadFile);
} catch (IOException e) {
return null;
}
//将上传的文件名称返回,注意,这里我们返回一个 服务器地址
return savepath+newFileName;
}
}
control业务层中的变量
#上传图片路径
file:
uploadPath: F:\\study\\javaNews\\src\\main\\resources\\static\\images\\
配置类 WebMvcConfg 定义静态资源映射目录
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
/**
* addPathPatterns 要拦截的路径
* excludePathPatterns 不拦截的路径
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AdminLoginInterceptor()).addPathPatterns("/user/**")
.excludePathPatterns("/user/login")
.excludePathPatterns("/user/logout")
.excludePathPatterns("/user/password")
.excludePathPatterns("/user/config/info");
}
/**
* 静态资源(自定义静态资源映射目录)
* @param registry
*/
@Value("${file.uploadPath}")
private String basepath;
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 前端浏览器访问路径带有/file/**就转到对应磁盘下读取图片【3种方法】
// registry.addResourceHandler("/images/**").addResourceLocations("file:F:/study/javaNews/src/main/resources/static/images/");
// registry.addResourceHandler("/images/**").addResourceLocations("file:"+basepath);
registry.addResourceHandler("/images/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/resources/static/images/");
//将所有/static/** 访问都映射到classpath:/static/ 目录下
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
2. 方法二:将图片上传到七牛云网站
html页面,form表单内容:
<div class="layui-form-item">
<label class="layui-form-label">照片:</label>
<div class="layui-input-block">
<input type="text" name="img" placeholder="请上传照片" lay-verify="required" readonly
id="img" autocomplete="off" class="layui-input" th:value="${bean.img}">
</div>
</div>
<div class="layui-form-item" id="demo2">
<div class="layui-inline">
<label class="layui-form-label">预览效果:</label>
<img class="layui-upload-img" id="demo1" th:src="${bean.img}" style="width: 9em;height: 9em">
</div>
</div>
layui -js代码:
//拖拽上传,普通图片上传
var uploadInst = upload.render({
elem: '#img'
, url: '/uploadMulit?type=goods'
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#demo1').attr('src', result); //图片链接(base64)
$('#demo2').show();
});
}
, done: function (res) {
//如果上传失败
if (res.code != 200) {
return layer.msg('上传失败');
} else {
$('#img').val(res.data);
return layer.msg('上传成功');
}
}
, error: function () {
}
});
表单提交:
//监听表单提交提交
form.on('submit(submit)', function (data) {
$.post("/admin/student/edit", data.field, function (res) {
if (res.code == 200) {
layer.msg(res.msg, {offset: 't',icon: 1, time: 1500}, function () {
location.href = res.data;
})
} else {
layer.msg(res.msg, {offset: 't',icon: 2, time: 1500});
}
});
return false;
});
control业务层:
@ResponseBody
@RequestMapping(value = "/uploadMulit", method = RequestMethod.POST)
public ResultMsg uploadImg(MultipartFile file) throws IOException {
if (file.isEmpty()) {
return ResultMsg.build(400, "文件为空,请重新上传");
}
byte[] bytes = file.getBytes();
String imageName = UUID.randomUUID().toString();
try {
//使用base64方式上传到七牛云
String url = QiniuCloudUtil.put64image(bytes, imageName);
System.out.println(url);
return ResultMsg.build(200, "文件上传成功", url);
} catch (Exception e) {
e.printStackTrace();
return ResultMsg.build(500, "文件上传发生异常!");
}
}
添加 QiniuCloudUtil 工具类:
public class QiniuCloudUtil {
// 设置需要操作的账号的AK和SK
private static final String ACCESS_KEY = "填你自己的";
private static final String SECRET_KEY = "填你自己的";
// 设置需要上传图片网址
private static final String DOMAIN = "http://upload.test.vip";
// 要上传的空间
private static final String bucketname = "test01";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
private static final String style = "你的样式";
public static String getUpToken() {
return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
}
//base64方式上传
public static String put64image(byte[] base64, String key) throws Exception{
String file64 = Base64.encodeToString(base64, 0);
Integer len = base64.length;
//华北空间使用 upload-z1.qiniu.com,华南空间使用 upload-z2.qiniu.com,北美空间使用 upload-na0.qiniu.com
String url = "http://upload-z2.qiniu.com/putb64/" + len + "/key/"+ UrlSafeBase64.encodeToString(key)
RequestBody rb = RequestBody.create(null, file64);
Request request = new Request.Builder()
.url(url)
.addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + getUpToken())
.post(rb).build();
//System.out.println(request.headers());
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
//如果不需要添加图片样式,使用以下方式
return DOMAIN+"/"+key;
//return DOMAIN + key + "?" + style;
}
// 普通删除(暂未使用以下方法,未体测)
public static void delete(String key) throws IOException {
// 实例化一个BucketManager对象
BucketManager bucketManager = new BucketManager(auth);
// 此处的33是去掉:http://ongsua0j7.bkt.clouddn.com/,剩下的key就是图片在七牛云的名称
key = key.substring(33);
try {
// 调用delete方法移动文件
bucketManager.delete(bucketname, key);
} catch (QiniuException e) {
// 捕获异常信息
Response r = e.response;
System.out.println(r.toString());
}
}
class Ret {
public long fsize;
public String key;
public String hash;
public int width;
public int height;
}
}
control业务层中的变量
# 七牛云上传
qiniu:
AccessKey: 填你自己的
SecretKey: 填你自己的
Bucket: lxsx
cdn:
prefix: http://q06ek3ls8.bkt.clouddn.com
# 上传文件的路径
basePath:
E:\Video\course
本文为原创作品,转载请注明出处
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/133729.html