smartUpload+jsp实现图片的预览和上传至服务器

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]);//现在只能是单选,所以我们直接[0]
			//当图片加载完毕之后,自动触发
			reader.onload=function(e){
				//得到图片的路径 result
				var result=this.result;
				console.log(result);
				//将结果放到img标签上
				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
	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);
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值