简单文件上传到服务器

来源:互联网 发布:linux 脚本 批量执行 编辑:程序博客网 时间:2024/06/07 01:35
package com.lean.zzh;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.util.List;import javax.management.RuntimeErrorException;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class FileUpload extends HttpServlet {/** * Constructor of the object. */public FileUpload2() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> *  * This method is called when a form has its tag value method equals to get. *  * @param request *            the request send by the client to the server * @param response *            the response send by the server to the client * @throws ServletException *             if an error occurred * @throws IOException *             if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 判断上传的表单的数据类型是不是multipart/form-databoolean isMulForm = ServletFileUpload.isMultipartContent(request);if (!isMulForm) {throw new RuntimeException("你的表单格式 不对");}// 常规的file上传逻辑// 创建‘能够创建上传文件对象’的“工厂”DiskFileItemFactory factory = new DiskFileItemFactory();// 上传文件的对象ServletFileUpload fileUpload = new ServletFileUpload(factory);// 设置字符编码fileUpload.setHeaderEncoding("utf-8");// 设置文件上传文件的大小 ,不可超过2MfileUpload.setFileSizeMax(2 * 1024 * 1024);// 设置文件总大小 , 不可超过5MfileUpload.setSizeMax(5 * 1024 * 1024);// 把表单提交过来的数据进行解析try {// FileItem表单项,有的项里面包含文件,有的不包含文件 对他们进行区别对待List<FileItem> fileItems = fileUpload.parseRequest(request);// 获取每一项的数据for (FileItem item : fileItems) {if (item.isFormField()) {// 它是一个普通数据项,不是文件项processFormField(item);} else {// 这是一个包含文件的项processFileUpload(item);}}} catch (FileUploadException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();}System.out.println(name + ":" + value);}// 对于包含文件的表单项private void processFileUpload(FileItem item) {// 在应用目录下保存这个文件 对于现在来讲就是Tomcat里String storeDirectory = getServletContext().getRealPath("/upload");// 创建文件的目录对象File realDirectory = new File(storeDirectory);// 判断目录是否存在if (!realDirectory.exists()) {// 如果不存在就创建  这个创建方法如果有字目录也会一并创建realDirectory.mkdirs();}byte[] dataByte = new byte[1024];int len = 0;InputStream in = null;FileOutputStream write = null;try {// 拿到文件的读取流in = item.getInputStream();// 得到文件上传的文件名String fileName = item.getName();// 获得保存上传文件的路径File realFile = new File(realDirectory, fileName);// 获得文件保存流write = new FileOutputStream(realFile);while ((len = in.read(dataByte)) != -1) {write.write(dataByte, 0, len);write.flush();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {// 关闭流 若过不关闭会发生操作系统中读者和写着问题,也就是,文件打不开,别占用着// 其实是 操作系统中读者一个锁,写者一个锁,当读者锁文件中写者无法访问,反之同样if (in != null) {try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (write != null) {try {write.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}/** * The doPost method of the servlet. <br> *  * This method is called when a form has its tag value method equals to * post. *  * @param request *            the request send by the client to the server * @param response *            the response send by the server to the client * @throws ServletException *             if an error occurred * @throws IOException *             if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}/** * Initialization of the servlet. <br> *  * @throws ServletException *             if an error occurs */public void init() throws ServletException {// Put your code here}}

原创粉丝点击