smartUpload+jsp实现图片的预览和上传至服务器
想要实现上传图片到服务器这个功能,我们需要去网上下载smartupload.jar工具包。
我这也是在网上找的一个链接(http://www.downcc.com/soft/14017.html)
1、首先在eclipse中搭建一个网页项目,这个项目主要包括两个网页,分别是reg.jsp和doUpload.jsp,同时将下载好的smartupload.jar这个工具包放在
WebContent的lib下面.
2、再前端页面中写出相应的html代码,一旦文件发生改变就进行图片的预览,具体
的代码如下,reg.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action='doUpload.jsp' method='post' enctype='multipart/form-data'>
账号:<input type="text" name='uname! id='uname'><br>
密码:<input type="password" name='pwd' id='pwd'><br>
年龄:<input type="age" name='age' id='age'><br>
<!-- accept属性 打开的文件的格式为图片 -->
<input type='file' name='files' id='files' accept='image/jpeg,image/png'><br/>
<input type='submit' value='注册' >
</form>
<img src="images/a.jpg" width='400px' height='320px' id='pic'>
<script>
var files=document.getElementById("files");
var pic=document.getElementById("pic");
files.onchange=function(){
var reader=new FileReader();
reader.readAsDataURL(files.files[0]);
reader.onload=function(e){
var result=this.result;
console.log(result);
pic.src=result;
}
}
</script>
</body>
</html>
3、现在开始在doUpload.jsp页面实现图片上传到服务器。在这之前一定要记住在
WebContent下面建一个存放图片的文件夹,这里是建的upload这个文件夹作为存放图
片。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import='com.jspsmart.upload.*' %>
<%
SmartUpload su=new SmartUpload();
su.initialize(pageContext);
su.setCharset("utf-8");
su.upload();
File file=su.getFiles().getFile(0);
String filepath="upload\\";
filepath +=file.getFileName();
file.saveAs(filepath);
%>