j2ee 文件上传功能

9 篇文章 0 订阅
 

环境 myEclipse9.1  servlet3.0

 

在网站中经常会遇到上传的功能,例如,用户上传自定义头像,上传共享资源,网站后台上传商品图片,如何实现此类功能? 现以上传图片为例,由客户端选择图片上传,服务器以字节流接受后,并保存在/images目录下,以jpg格式保存。

 

首先,如何让用户在客户端选择图片,在html中有表单对象标签

 

<form action="servlet/FileServlet" method="post"/>
   	上传图片:<input type="file" name="fileUp"/><input type="submit" value="上传"/>
</form>



 

由此可见input格式选为file则可以选择文件路径,

以下为服务器端代码

 

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("GBK");
		String clientPath = request.getParameter("fileUp");
		System.out.println(clientPath);
		
		File clientFile = new File(clientPath);
		FileInputStream inputStream = new FileInputStream(clientFile);
		
		ServletContext context = this.getServletContext();
		
		String serverPath = context.getRealPath(context.getContextPath());
		
		String path = serverPath+"\\image";
		
		File imgPath = new File(path);
		System.out.println(imgPath.mkdir());
		
		
		File fileImage = new File(path,clientFile.getName());
		if(!fileImage.exists()){
			fileImage.createNewFile();
		}
		
		FileOutputStream outputStream  = new FileOutputStream(fileImage, true);
		
		byte[] temp = new byte[128];
		int size = (int)clientFile.length();
		while(inputStream.read(temp)!=-1){
			outputStream.write(temp, 0, temp.length);
		}
		
		outputStream.close();
		inputStream.close();
	}

 


 

首先我们用request接受到了客户端传送的路径,此路径是由客户端浏览器程序发送,(注意,此路径仅一次有效,) ,使用file创建了一个文件对象,之后我们通过环境上下文获取了项目的绝对路径,并拼出images的绝对路径,使用io流从客户端循环读一定量的字节,并写入文件。

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值