这几天做项目需要用到图片上传的内容,以前没有仔细处理过这个问题,现在才发现原来
<input type="file">
真的不是一个好用的控件。经过了使用多种图片处理图片,现在逐渐地对如何上传图片进行一个总结,方便以后的使用。
- 图片预览功能
- 上传图片到服务器
- input按钮美化
图片预览功能
其实在使用到
<input type="file">
的时候,通常还会有一个特殊的需求,就是在点击上传图片按钮之后,能够实现在本地预览图片。
<img id="show" src="">
<input type="file" id="photo" onchange="change(this.id,'show')">
<script>
function change(sourceId, targetId) {
if (typeof FileReader === 'undefined') {
alert('Your browser does not support FileReader...');
return;
}
var reader = new FileReader();
//onload表示的是成功读取
reader.onload = function(e) {
var img = document.getElementById(targetId);
img.src = this.result;
}
reader.readAsDataURL(document.getElementById(sourceId).files[0]);
}
</script>
关于FileReader这个接口的具体介绍,看一下的博客 预览图片
由于浏览器不同,所获取到的图片url的方法也不一样,上面的方法是基于接口来实现的,接下来通过判断不同的浏览器来展示所上传的图片。
<img id="show" src="">
<input type="file" name="photo" id="photo" onchange="preImg(this.id, 'show')">
function getFileUrl(sourceId) {
var url;
if (navigator.userAgent.indexOf("MSIE") >= 1 && !(navigator.userAgent.indexOf("MSIE 10.0") > 0) ) { // IE10取消了滤镜
//url = document.getElementById(sourceId).value;
document.all.imgOne.select();
$("#preview").focus();
url = document.selection.createRange().text;
} else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}else if(navigator.userAgent.indexOf("MSIE 10.0") > 0){
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}else if(navigator.userAgent.indexOf("MicroMessenger") > -1){//微信浏览器
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}else{
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}
return url;
}
function preImg(sourceId, targetId) {
var url = getFileUrl(sourceId);
var imgPre = document.getElementById(targetId);
if(window.navigator.userAgent.indexOf("MSIE") >= 1 && !(navigator.userAgent.indexOf("MSIE 10.0") > 0) ) {
var picpreview=document.getElementById("preview");
picpreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = url;
}else{
imgPre.src = url;
}
}
一看就知道哪一种的更加复杂的了,同时实现预览也可以通过将文件压缩之后再预览,以下的方法就是通过这样的方式来实现的。
<img id="show" src="">
<input type="file" name="photo" id="photo" onchange="change()">
在javascript中使用压缩插件来实现,使用的插件是localResizeIMG压缩
function change(){
var files = $("#photo")[0].files[0];
lrz(files)
.then(function (rst) {
console.log(rst);
$("#show").attr("src",rst.base64);
})
.catch(function (err) {
})
.always(function () {
});
}
上传图片到服务器
spring mvc + form表单的实现
前端上传代码:
<form action="url/success" method="post" enctype="multipart/form-data">
<input id="photo" name="photo" type="file">
<input id="submit"
</div>
后端处理代码
@RequestMapping("/success")
public String success(HttpServletRequest request,@RequestParam(value="photo",required=false) MultipartFile file){
String name ="img";
//服务器地址
String pathRoot = request.getSession().getServletContext().getRealPath("");
String path="";
if(!file.isEmpty()){
String contentType=file.getContentType();
String imageName=contentType.substring(contentType.indexOf("/")+1);
//图片相对地址
path="/img/schedule/"+name+"."+imageName;
try {
//将图片保存到以下的文件夹中
file.transferTo(new File(pathRoot+path));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "jsp/success";
}
同时需要在spring-mvc配置文件中配置文件上传的内容
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>
关于其他方法上传待续
input按钮美化
html自带的input上传文件按钮美观程度达不到许多产品的要求,所以只能在自己在input按钮的基础上做工作。
使用<span>
标签和<input>
标签重叠在一起来完成这个功能,具体代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>美化input按钮</title>
<style type="text/css">
#div1{
position:relative;
}
#div2{
position:absolute;
left:30px;
top:30px;
}
#div3{
position:absolute;
left:30px;
top:30px;
}
span{
padding: 5px;
background: #6495ED;
border: 2px solid #436EEE;
}
input{
width: 78px;
opacity: 0;
}
</style>
</head>
<body>
<div style="border: 1px solid #000;width: 100px;height: 100px">
<img id="show" width="100" src="">
</div>
<div id="div1">
<div id="div2">
<span>上传文件</span>
</div>
<div id="div3">
<input type="file" name="photo" id="photo" onchange="change(this.id,'show')">
</div>
</div>
<script type="text/javascript">
function change(sourceId, targetId) {
if (typeof FileReader === 'undefined') {
alert('Your browser does not support FileReader...');
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var img = document.getElementById(targetId);
img.src = this.result;
}
reader.readAsDataURL(document.getElementById(sourceId).files[0]);
}
</script>
</body>
</html>
使用jquery里面的trigger()方法来出发change方法,然后把input的display变成none,再用点击a标签的动作来触发input的change方法,具体如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="tools/jquery-2.2.3.js"></script>
<style type="text/css">
#to{
padding: 5px;
text-decoration-line: none;
background: #6495ED;
color: #000;
}
#photo{
display: none;
}
</style>
</head>
<body>
<div style="border: 1px solid #000;width: 100px;height: 100px">
<img id="show" width="100" src="">
</div>
<div style="margin-top: 10px;">
<a id="to" href="javascript:;">
上传
</a>
<input type="file" id="photo" name="photo">
</div>
<script type="text/javascript">
$(function () {
// body...
$("#to").click(function(){
$("input[type='file']").trigger('click');
});
$("input[type='file']").change(function(){
if (typeof FileReader === 'undefined') {
alert('Your browser does not support FileReader...');
return;
}
var reader = new FileReader();
reader.onload = function(e) {
$("#show").attr("src",this.result);
}
reader.readAsDataURL($("#photo")[0].files[0]);
});
});
</script>
</body>
</html>