利用Servlet上传文件

package com.demo;

import java.io.*;
import java.io.IOException;
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 UploadServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out=response.getWriter();
		response.setContentType("text/html;charset=gb2312");
		response.setCharacterEncoding("gb2312");
		request.setCharacterEncoding("gb2312");
		//定义上载文件的最大字节 
		int MAX_SIZE = 102400 * 102400; 
		 // 创建根路径的保存变量 
		String rootPath; 

		//声明文件读入类 和输出类
		DataInputStream in = null; 
		FileOutputStream fileOut = null; 

		 //获得服务器的名字 
		String serverName = request.getServerName(); 
		out.print("request.getServerName()="+serverName+"<br>"); 

		 //取得服务器端应用程序的绝对地址 
		String realPath = request.getRealPath(serverName); 
		out.println("request.getRealPath(serverName)="+realPath+"<br>"); 
		out.println("OK<br>");
		realPath = realPath.substring(0,realPath.lastIndexOf("\\")); 
		 //创建文件的保存目录 
		rootPath = realPath + "\\upload\\"; 
		out.println("rootPath="+rootPath); 
		
		 //取得客户端上传的数据类型 
		String contentType = request.getContentType(); 
		out.println("<p>contentType = " + contentType + "</p>"); 
	    try{ 
	    	if(contentType.indexOf("multipart/form-data") >= 0){ 
	    		//读入上传的数据 
	    		in = new DataInputStream(request.getInputStream()); 
	    		int formDataLength = request.getContentLength(); 
	    		if(formDataLength > MAX_SIZE){ 
	    			out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>"); 
	    			return; 
	    		} 
	    		//保存上传文件的数据 
	    		byte dataBytes[] = new byte[formDataLength]; 
	    		int byteRead = 0; 
	    		int totalBytesRead = 0; 
	    		//上传的数据保存在byte数组 
	    		while(totalBytesRead < formDataLength){ 
	    			byteRead = in.read(dataBytes,totalBytesRead,formDataLength); 
	    			totalBytesRead += byteRead; 
	    			System.out.print("totalBytesRead:"+totalBytesRead);
	    		} 
	    		//根据byte数组创建字符串 
	    		String file = new String(dataBytes); 
	    		out.println("<br><br>file content:"+file); 
	    		
	    		//取得上传的数据的文件名 
	    		String saveFile = file.substring(file.indexOf("filename=\"") + 10); 
	    		saveFile = saveFile.substring(0,saveFile.indexOf("\n")); 
	    		saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\"")); 
	    		int lastIndex = contentType.lastIndexOf("="); 
	    		//取得数据的分隔字符串 
	    		String boundary = contentType.substring(lastIndex + 1,contentType.length()); 
	    		//创建保存路径的文件名 
	    		String fileName = rootPath + saveFile; 
	    		out.print("<br><br>fileName="+fileName); 
	    		
	    		int pos; 
	    		pos = file.indexOf("filename=\""); 
	    		pos = file.indexOf("\n",pos) + 1; 
	    		pos = file.indexOf("\n",pos) + 1; 
	    		pos = file.indexOf("\n",pos) + 1; 
	    		//pos是文章开始的第一个字符所在的位置
	    		int boundaryLocation = file.indexOf(boundary,pos) - 4; 
	    		out.println("<br>boundaryLocation="+boundaryLocation); 
	    		//取得文件数据的开始的位置 
	    		int startPos = ((file.substring(0,pos)).getBytes()).length; 
	    		out.println("<br>startPos="+startPos); 
	    		//取得文件数据的结束的位置 
	    		int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length; 
	    		out.println("<br>endPos="+endPos); 
	    		
	    		//检查上载文件是否存在 
	    		File checkFile = new File(fileName); 
	    		if(checkFile.exists()){ 
	    			out.println("<p>" + saveFile + " has existed.</p>"); 
	    			return;
	    		} 
	    		
	    		//检查上载文件的目录是否存在 
	    		File fileDir = new File(rootPath); 
	    		if(!fileDir.exists()){ 
	    			fileDir.mkdirs(); 
	    		} 
	    		
	    		//创建文件的写出类 
	    		fileOut = new FileOutputStream(fileName); 
	    		//保存文件的数据 
	    		fileOut.write(dataBytes,startPos,(endPos - startPos)); 
	    		fileOut.close(); 
	    		out.println("<P>" + saveFile + " upload successfully.</p>"); 
	       }else{ 
		        out.println("<p>datatype is not multipart/form-data</p>"); 
	       } 
	    }catch(Exception ex){ 
		   throw new ServletException(ex.getMessage()); 
	    } 
	}

}
发布了395 篇原创文章 · 获赞 130 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_40507857/article/details/89673995