JavaEE--------上传

本文详细介绍两种文件上传方法:一是通过底层方法演示表单提交过程;二是利用Apache文件上传工具实现文件上传,包括如何使用commons-fileupload和commons-io库进行文件处理,并介绍了文件上传过程中的关键步骤,如设置文件大小限制、解决中文乱码问题等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.用底层的方法演示上传,上传表单提交方式属性设置method="post" enctype="multipart/form-data",普通表单的属性是POST1: application/x-www-form-urlencoded
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploadServlet0 extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		InputStream in  = request.getInputStream();//从request拿到输入流对象
		BufferedReader br = new BufferedReader(new InputStreamReader(in));//用转换包装后再用缓冲字符流包装,加速
		String line=null;
		while( (line=br.readLine())!=null){
			System.out.println(line);
		}
	}

}

<span style="font-size:14px;"><strong>2.</strong></span><span style="font-size:18px;"><strong>使用apache文件上传工具实现文件上传,用到两个jar包:commons-fileupload-1.2.2.jar;commons-io-2.1.jar</strong></span><pre name="code" class="java"><pre name="code" class="java">import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class UploadServlet2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		//获取GET方式的url中“?”号后面的部分
		//http://localhost:8080/servletDemo3/upload?name=Jack&sex=male
		String qStr = request.getQueryString();
		System.out.println("qStr: "+qStr);//qStr: name=Jack&sex=male
		
		out.println("不支持GET方式上传文件");
		
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//普通的form表单(POST1: application/x-www-form-urlencoded ),下面这句可以设置普通表单组件内容的编码(能够解决它们的中文乱码问题)
		request.setCharacterEncoding("utf-8");//※如果是含上传文件的表单(POST2: multipart/form-data),该句只能设置所上传文件的文件名中的编码(解决它的中文乱码)。但不能解决普通表单组件的乱码(不能设它编码)
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		//▲1防黑: 防护前端采用POST1方式提交
		//法1
		/*
		String type=request.getContentType();
		if(!type.contains("multipart/form-data")){
			out.println("不支持普通表单提交");
			return;
		}
		*/
		
		//法2     //利用工具
		boolean boo = ServletFileUpload.isMultipartContent(request);
		if(!boo){
			out.println("不支持普通表单提交");
			return;
		}
		
		
		//在服务器上,为所有上传文件指定一个存放目录
		String path = getServletContext().getRealPath("/upload");
		File dir = new File(path);
		if(!dir.exists()){
			dir.mkdirs();
		}
		
		File file = new File("d:/a");
		DiskFileItemFactory f = new DiskFileItemFactory(1024*8,file);//设置临时文件缓冲区大小
		ServletFileUpload upload = new ServletFileUpload(f);//上传工具
		upload.setFileSizeMax(1024*1024*5);//设置单个文件最大为5M
		upload.setSizeMax(1024*1024*8);//所有上传文件大小之和的最大值,8M
		
		//▲4上传进度监听
		upload.setProgressListener(new ProgressListener(){
			private double pre=0D;
			@Override//参数1:已上传多少字节  参数2:一共多少字节   参数3:第几个文件(序号从1开始)
			public void update(long pByteRead, long pContentLength, int pItems) {
				double d = 1.0*pByteRead/pContentLength*100;
				System.out.println(d+"%");
//				if(pre!=d){
//					System.out.println(d+"%");
//					pre=d;
//				}
			}
		});
		
		//使用工具解析
		try {
			List<FileItem> list = upload.parseRequest(request);
			for(FileItem ff:list){
				if(ff.isFormField()){//普通表单组件 <input type=text,checkbox,radio,password ...
					String desc = ff.getString("utf-8");//※在POST2下,用指定编码的方式解决中文乱码
					System.out.println("desc:"+desc);
				}else{
					
					//▲2防护: 过滤掉没有选择文件的 空文件组件
					//ff.getSize();//返回当前文件的大小
					long size = ff.getSize();
					//System.out.println("size: "+size);
					if(size==0){
						continue;
					}
					
					//System.out.println("文件内容类型:"+ff.getContentType());
					//System.out.println("文件名:"+ff.getName());//上课时间.txt
					String fileName = ff.getName();
					//System.out.println("************");
					String uuid = UUID.randomUUID().toString().replace("-", "");
					String ext = fileName.substring(fileName.lastIndexOf("."));
					String newFileName = uuid+ext;
					
					//▲3 文件打散技术
					String dir1 = Integer.toHexString( uuid.hashCode()&0xf );
					String dir2 = Integer.toHexString( (uuid.hashCode()&0xf0)>>4 );
					File fDir = new File( path+"/"+dir1+"/"+dir2);
					if(!fDir.exists()){
						fDir.mkdirs();
					}
					String path2 = path+"/"+dir1+"/"+dir2;
					
					
					FileUtils.copyInputStreamToFile(ff.getInputStream(),new File(path2+"/"+newFileName));//写活
					
				}
			}
			
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
	}

}
3.附加一个进度条前端技术演示
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title><span style="font-family: Arial, Helvetica, sans-serif;">进度条前端技术演示</span><span style="font-family: Arial, Helvetica, sans-serif;"></title></span>
  </head>
  
  <body>
    <h2>进度条前端技术演示</h2>
    <div style="border:1px solid red;width:400px;height:30px;">
    	<div id="dataDiv" style="background: red; width:0%;height:100%"/>
    </div>
    <button onclick="start();">Start</button>
    <button onclick="stop();">Stop</button>
    <button onclick="restart();">ReStart</button>
    <script type="text/javascript">
    	var tm,a;
    	function start(){
    		tm = window.setInterval(run, 1000);
    		a=0;
    	}
    	function restart(){
    		window.clearInterval(tm);
    		tm = window.setInterval(run, 1000);
    		a=0;
    	}
    	function stop(){
    		window.clearInterval(tm);
    	}
    	function run(){
    		a+=10;
    		if(a>100){
    			window.clearInterval(tm);
    			return;
    		}
    		var div = document.getElementById("dataDiv");
    		div.style.width=a+"%";
    	}
    </script>
    
    <br/><br/><br/><br/>
    <img src="/servletDemo3/imgs/1.jpg" /><br/>
    
    <!-- 注意,后台存储的资源文件不允许使用中文,否则前端无法访问的 -->
    <img src="/servletDemo3/imgs/图片2.jpg" /><br/>
  </body>
</html>


<pre name="code" class="html">    




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值