JSP实现图片上传和参数传递
这里借助smart upload进行上传
导入Jar包
直接放到WEB-INF下的lib即可
未生效就Add to Build Path一下
上传页面
add.html
为了上传图片,需要给form表单设置post方式提交以及二进制编码
<form method="post" enctype="multipart/form-data">
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加</title>
</head>
<body>
<div class="main-form">
<form action="add_controller.jsp" method="post" enctype="multipart/form-data">
<h3 class="title">添加数据</h3>
<div class="item">
<label >书名:</label>
<input type="text" name="bookname"/>
</div>
<div class="item">
<label >图片:</label>
<input class="pic-upload" type="file" name="uploadFile" />
</div>
<div class="item">
<label >简介:</label>
<input type="text" name="introduce"/>
</div>
<div class="btns">
<input type="submit" class="sure" value="确认"></input>
<input type="button" class="cancel" onclick="cancel()" value="取消"></input>
</div>
</form>
</div>
</body>
</html>
处理上传页面
- 接收参数要用mySmartUpload.getRequest().getParameter,不能用request.getParameter,且要在mySmartUpload完成initialize后
- 最好在项目的WebContent下建一个res文件夹,以防路径错误
- mySmartUpload.save(uploadPath);执行完这句时自动完成图片上传
- System.out.print(“已将图片保存,”+“网络地址为:”+URL+"\n真实地址为:"+uploadPath);一句在控制台输出了保存的地址,可以再浏览器中直接使用网络地址,具体如下:
add_controller.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String uploadPath = request.getSession().getServletContext().getRealPath("/res");
com.jspsmart.upload.SmartUpload mySmartUpload = new com.jspsmart.upload.SmartUpload();
mySmartUpload.initialize(pageContext);
mySmartUpload.service(request, response);
mySmartUpload.upload();
String fn = mySmartUpload.getFiles().getFile(0).getFileName();
mySmartUpload.save(uploadPath);
//第一个为项目名,第二个为上传文件的名字
String URL = String.format("http://localhost:8080%s/res/%s", pageContext.getServletContext().getContextPath(),fn);
System.out.print("已将图片保存,"+"网络地址为:"+URL+"\n真实地址为:"+uploadPath);
String str = mySmartUpload.getRequest().getParameter("bookname");
out.print(str);
%>
</body>
</html>
smart upload的jar包
链接:https://pan.baidu.com/s/1zo7lhPDsTKDo9SdTOCsqFw
提取码:9vx8