javaweb之--文件上传

1.增强型for循环,不可以移除元素。java.util.ConcurrentModificationException
public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<String> list=new ArrayList<String>();
		list.add("1");
		list.add("2");
		list.add("3");
		list.add("4");
		list.add("5");
		for (String string : list) {
			list.remove(string);
		}
		System.out.println("执行结束");
	}
}

2.文件上传的servlet

package com.qfedu.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet2
 */
@WebServlet("/upload2")
public class UploadServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadServlet2() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 判断上传的表单的数据类型是不是multipart/form-data
		boolean isMultipartForm = ServletFileUpload.isMultipartContent(request);
		if (!isMultipartForm) {
			throw new RuntimeException("表单格式不正确。");
		}

		// 常规的file上传逻辑
		// 能够创建一个“文件上传对象”的工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 文件上传对象
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		// 设置字符编码
		fileUpload.setHeaderEncoding("utf-8");

		// 设置上传文件的大小,不可超过2M
		fileUpload.setFileSizeMax(2 * 1024 * 1024);

		// 设置整个表单的总大小,不可超过5M
		fileUpload.setSizeMax(5 * 1024 * 1024);

		try {
			// 解析一个请求
			// 其实就是按照http报文的格式,把request分解为一个一个的item
			// FileItem就是表单项
			List<FileItem> fileItems = fileUpload.parseRequest(request);
			for (FileItem item : fileItems) {
				if (item.isFormField()) {
					// 它是一个普通数据项
					processFormField(item);
				} else {
					// 它是一个文件项
					processFileUpload(item,response);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void processFormField(FileItem item) {
		// 得到名字
		String name = item.getFieldName();
		String value = "";
		try {
			value = item.getString("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("name=" + name + "; value=" + value);
	}

	//在web工程中,WEB-INF目录是受保护的目录。
	//如果文件保存在WEB-INF下,浏览器无法访问到,进而所谓的“木马”无法运行。
	private void processFileUpload(FileItem item,HttpServletResponse response) {
		// 首先得到应用(网站)目录,用于保存文件
		//String storeDirectory = getServletContext().getRealPath("/WEB-INF/upload");
		String storeDirectory = getServletContext().getRealPath("/upload");
		// 创建文件的目录对象
		File realDirectory = new File(storeDirectory);
		if (!realDirectory.exists()) {
			realDirectory.mkdirs();
		}
		// 怎么保存?
		// 读一点写一点
		InputStream in = null;
		FileOutputStream fos = null;

		try {
			// 拿到文件的读取流
			in = item.getInputStream();
			// 拿到文件名
			String fileName = item.getName();
			//不同浏览器文件名格式不一致
			//ie:D:\temp\temp.jpg
			//火狐谷歌:temp.jpg
			
			fileName=fileName.substring(fileName.lastIndexOf(File.separator)+1);
			//假如asdf.jsp
			//是否以.jsp结尾
			//p.jpg
			//alsdjkfl.jspalksjdflkaj.jsp
			if(fileName.lastIndexOf(".jsp")==fileName.length()-4) {
				response.getWriter().print("您的ip地址已经记录,请勿尝试非法操作,本网站保留追责权利。");
				throw new RuntimeException("您的ip地址已经记录,请勿尝试非法操作,本网站保留追责权利。");
			}
			//至此,文件不是以.jsp结尾的了
			//许多用户上传文件,文件名相同会被覆盖。
			//UUID,标识唯一的字符串
			//使用uuid作为文件名的前缀
			fileName=UUID.randomUUID().toString()+"_"+fileName;
			
			//获取子目录
			String childDirectory=getChildDirectory(realDirectory, fileName);
			
			
			
			File file = new File(realDirectory, childDirectory+File.separator+fileName);
			fos = new FileOutputStream(file);
			byte[] arr = new byte[1024];
			int len = 0;
			for (; (len = in.read(arr)) != -1;) {
				fos.write(arr, 0, len);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	//创建两级子目录,每一级16个,并且使用文件名的hashcode将文件分散在每一个目录中
	private String getChildDirectory(File realDirectory,String fileName) {
		int hashCode=fileName.hashCode();
		//code的形式是1ef39b
		String code=Integer.toHexString(hashCode);
		//利用hashcode的十六进制的前两位,作为两级子目录的名字
		String childDirectory=code.charAt(0)+File.separator+code.charAt(1);
		//子目录如同:upload/a/c/     upload/1/a/
		File dir=new File(realDirectory,childDirectory);
		if(!dir.exists()) {
			dir.mkdirs();
		}
		return childDirectory;
	}
	
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

3.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload2" method="post" enctype="multipart/form-data">
<input type="file" name="icon"/>
<input type="text" name="username"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

4.icon.html读取文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<img id="img" width="200px" height="120px" src="upload/b/b/639bddf7-d0d9-47a7-9c58-f921839b140b_qflogo.jpg"/>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41813207/article/details/80335385
今日推荐