servlet文件的上传与下载基本步骤

servlet文件的上传与下载基本步骤


一、准备:
commons-fileupload-1.4.jar
commons-io-2.6.jar
二、上传
1.设置请求字符集

req.setCharacterEncoding("UTF-8");

2.创建文件上传工厂

DiskFileItemFactory factory = new DiskFileItemFactory();

3.创建文件上传组件

ServletFileUpload upload = new ServletFileUpload(factory);

4.获取所有文件项

List<FileItem> items = upload.parseRequest(req);

5.遍历items获取所有文件,可以通过!item.isFormField()判断是否是文件。

三、下载
下载分为两种
(一)下载到浏览器的内存中
1.获取文件名(由前端传递)

String filename = req.getParameter("filename");

2.获取文件在服务器的存储地址

realPath = req.getServletContext().getRealPath("/image");

3.组合出文件

File file = new File(realPath,filename);

4.读取文件

InputStream input = new FileInputStream(file);

5.获取响应输出流

OutputStream output = resp.getOutputStream();

6.真正的读写

IOUtils.copy(input,output);

7.关闭相关流

output.close();input.close();

(二)下载到用户本地,带弹窗
在(一)的第4步之前加入如下步骤
1.获取文件类型(由前端传递)

String type = req.getParameter("type");

2.设置文本相应格式

resp.setContentType(type);

3.设置文本响应长度

resp.setContentLength((int) file.length());

4.设置响应头(有弹框,下载到本地),其中属性filename可以没有。

resp.setHeader("Content-DisPosition","attachment;filename="+filename);

其余步骤与(一)中相同。
四、上传与下载的前端操作
(一)上传
1.submit直接上传
2.ajax上传
使用FormData

xhr.open("post","improc");

xhr.send(formData);

(二)下载
记住传递需要的参数即可。
五、代码
(一)上传

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("begin0");
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		//创建文件上传工厂
		System.out.println("creat factory");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//创建文件上传组件
		System.out.println("creat upload");
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			//获取所有文件
			List<FileItem> items = upload.parseRequest(req);
			System.out.println("1");
			String responseText = "";
			Map <String,String> map=new HashMap<>();
			String realPath = req.getServletContext().getRealPath("/image");
			String path="";
			String name="";
			for(FileItem i:items) {
				if(!i.isFormField()) {
					name = UUID.randomUUID()+i.getName();
					path=realPath+"/"+name;
					File f=new File(path);
					i.write(f);
					System.out.print(f.getPath());
					map.put(i.getFieldName(),path);
					map.put("type", i.getContentType());
				}else {
					map.put(i.getFieldName(),i.getString());
				}
			}
			//ImageSeparation(map.get("alg"),Integer.parseInt(map.get("param")),map.get("img"));
			
			String json = "{\"filename\": \""+name+"\"}";
			json=String.format("{\"filename\": \"%s\",\"type\":\"%s\"}",name,map.get("type"));
			
			resp.getWriter().write(json);
			return;
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}

(二)下载

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String flag = req.getParameter("flag");
		if("1".equals(flag)) {
			String filename = req.getParameter("filename");
			String realPath = req.getServletContext().getRealPath("/image");
			File file = new File(realPath,filename);
			//读取文件
			InputStream input = new FileInputStream(file);
			
			//写到本地硬盘(浏览器的内存)
			OutputStream output = resp.getOutputStream();
			//真正的读写
			IOUtils.copy(input,output);
			output.close();
			input.close();
		}else {
			String filename = req.getParameter("filename");
			String realPath = req.getServletContext().getRealPath("/image");
			File file = new File(realPath,filename);
			String type = req.getParameter("type");
			//设置响应文本格式
			resp.setContentType(type);
			//设置长度
			resp.setContentLength((int) file.length());
			//弹框设置响应头
			resp.setHeader("Content-DisPosition","attachment;filename="+filename);
			//读取文件
			InputStream input = new FileInputStream(file);
			
			//写到本地硬盘(浏览器的内存)
			OutputStream output = resp.getOutputStream();
			
			IOUtils.copy(input,output);
			output.close();
			input.close();
		}
		
	}

(三)前端

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href=<%=basePath%> />
	<meta charset="UTF-8">
	<title>基于聚类的图像分割</title>
	<link rel="stylesheet" type="text/css" href="themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="themes/icon.css">
	<link rel="stylesheet" type="text/css" href="css/demo.css">
	
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.easyui.min.js"></script>
	
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript" src="js/jquery.js"></script>
		 
	<style scoped="scoped">
		.textbox{
			height:20px;
			margin:0;
			padding:0 2px;
			box-sizing:content-box;
			width: 150px;
		}
		.combobox{
			height:23px;
			margin:0;
			padding:0 2px;
			box-sizing:content-box;
			width: 150px;
		}
		input[type="button"]{
			height:20px;
			margin:0;
			padding:0 2px;
			box-sizing:content-box;
			width: 150px;
		}
		#submit{
			height:25px;
			width: 225px;
		}
		img{
			width: 500px;
		}
	</style>
	<script type="text/javascript">
	function optChange(){
		//响应算法改变
	}
	//选择图片按钮被点击
	function imgBtnClk(id){
		//点击被隐藏的文件选择对话框
		$("#"+id).click();
	}
	function imageChange(e){
		var tgt=e.target;
		var src=tgt.value;
		$("#imageSrc").val(src);
		
		var file=tgt.files[0];
		var reader = new FileReader();
		reader.addEventListener("load", function() {
			$("#imageShow").attr("src",reader.result);
        }, false);
		reader.readAsDataURL(file);
	}
	
	function subCilck(){
		var form = document.getElementById("form");
		//使用formdata来传递参数
		var formData = new FormData();
		formData.append("alg",$("#algSelect").val());
		formData.append("param",$("#param").val());
		var imgSel = document.getElementById("imageSelect");
		var img = imgSel.files[0];
		formData.append("img",img);
		//使用json来传递参数
		//获取ajax对象
		var xhr=new XMLHttpRequest();
		//重载onreadystatechange函数
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4){
				alert(xhr.responseText);
				responseObject = JSON.parse(xhr.responseText);
				var aa= "<a href='download?flag=1&filename="+responseObject.filename+"'>下载(1)</a> <a href='download?flag=2&filename="+responseObject.filename+"&type="+responseObject.type+"'>下载(2)</a>"
				$("#imgs").html(aa);
			}
			
		}
		//打开请求
		xhr.open("post","improc");
		//发送请求
		xhr.send(formData);
	}
	</script>
</head>
<body>
	<div align="center">
	<div id="main" style="display: inline-block;">
	<h2>图像分割</h2>
	<p>选择图片、设置参数,点击确认开始分割</p>
	    <form id="form" method="post" enctype="multipart/form-data">
	    	<table cellpadding="5">
	    		<tr>
	    			<td>聚类算法:</td>
	    			<td>
	    				<select class="combobox" id="algSelect" name="alg">
		    				<option value="kmeans">k均值(k-means)</option>
		    				<option value="meanshift">均值漂移(mean-shift)</option>
	    				</select>
	    			</td>
	    		</tr>
	    		<tr>
	    			<td>参数:</td>
	    			<td><input type="number" class="textbox" name="param" id="param" min="1" value="1"></input></td>
	    		</tr>
	    		<tr>
	    			<td>图片:</td>
	    			<td>
		    			<input type="file" name="imageSelect" id="imageSelect" style="display: none;" onchange="imageChange(event)">
		    			<input class="textbox" type="text" name="imageSrc" id="imageSrc" readonly="readonly" >
	    			</td>
	    		</tr>
	    		<tr>
	    			<td></td>
	    			<td><input type="button" id="imageBtn" value="选择图片" onclick="imgBtnClk('imageSelect')"></td>
	    		</tr>
	    		<tr>
	    			<td colspan="2"  align="center"><input type="button" id="submit" value="确定" onclick="subCilck()"></td>
	    		</tr>
	    	</table>
	    </form>
	</div>
	<img id="imageShow" alt="" src=""  align="top">
</div>
<div>
	<div id="imgs" style="width:500px;height: 200px;border: 1px solid;margin:0px auto;"></div>
</div>


</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值