servlet简单上传示例

本文深入探讨了Java中文件上传处理的实现细节,包括初始化配置、上传表单参数保存及错误处理流程。

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

/*
 * @(#)FileUpload.java 1.0 Created on 2005-9-23
 * 
 * Copyright 2005 LCW. All rights reserved.
 */

package com.fu.tools;

import java.io.*;
import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.servlet.*;
import javax.servlet.http.*;

public class MyFileUpload extends HttpServlet {
	/** 默认输出页面 */
	private static final String html_upload = "luntan_imgupload.htm";

	private static final String html_error = "luntan_error.htm";

	/** 输出页面所在的路径 */
	private static String output_path;

	/** 输出页面所在的虚拟WEB路径 */
	private static String html_webRoot;

	/** 信息文件名 */
	private static String props_file;
	
	/** 设定上传文件的最大尺寸为128k */
	static final int MAX_SIZE = 131072;

	/** 实例化一个参数保存目录 */
	private String uploadPath;
	/** 实例化一个参数保存目录 */
	private String uploadRoot;

	/**
	 * servlet初始化
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		/** 取得保存文件的目录 */
		uploadPath = config.getInitParameter("UploadPath");
		if (uploadPath == null) {
			uploadPath = "/";
		}
		/** 取得保存文件的目录 */
		uploadRoot = config.getInitParameter("UploadRoot");
		if (uploadRoot == null) {
			uploadRoot = "/";
		}
		/** 从资源文件中读取配置参数信息 */
		ResourceBundle rsBundle = ResourceBundle.getBundle("sysinfo");
		output_path = rsBundle.getString("HTML_FILEPATH");
		html_webRoot = rsBundle.getString("HTML_WEBROOT");
		props_file = rsBundle.getString("PROP_FILENAME");
	}

	/**
	 * 取得上传表单参数并保存文件信息
	 * 
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @throws ServletException,
	 *             IOException
	 * @author fulin
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/** 显示页面 */
		String output_html = null;
		/** 客户端的语言 */
		String strLanguage = null;
		/** 设置页面显示项Hashtable */
		Hashtable htmlHashtable = new Hashtable();
		/** 页面显示信息资源表 */
		ResourceBundle rsBundle = null;
		
		String successMessage = "Upload file successed.";

		DataInputStream in = null; 
		FileOutputStream fileOut = null;
		/** 取得客户端的传递类型 */
		String contentType = request.getContentType();
		try {
			/** 客户端的语言 */
			strLanguage = request.getHeader("Accept-Language");
			/** 根据信息文件名取得信息资源表 */
			rsBundle = PropResource.getResource(props_file, strLanguage);
			/** 国际字符表示符(识别符)转换 */
			strLanguage = ComTools.languageConver(strLanguage);
			
			/** 确认数据类型是 multipart/form-data */
			if (contentType != null
					&& contentType.indexOf("multipart/form-data") != -1) {
				/** 取得上传文件流的字节长度 */
				int fileSize = request.getContentLength();
				
				if (fileSize > MAX_SIZE) {
					successMessage = "Sorry, file is too large to upload.";
					return;
				}
				
				/** 读入上传的数据 */
				in = new DataInputStream(request.getInputStream());

				/** 保存上传文件的数据 */ 
				byte dataBytes[] = new byte[fileSize]; 
				int byteRead = 0; 
				int totalBytesRead = 0; 
				/** 上传的数据保存在byte数组 */
				while(totalBytesRead < fileSize){ 
					byteRead = in.read(dataBytes, totalBytesRead, fileSize); 
					totalBytesRead += byteRead; 
				} 
				int i = dataBytes.length;
				/** 根据byte数组创建字符串 */
				String file = new String(dataBytes);
				i = file.length();
				/** 取得上传的数据的文件名 */
				String upFileName = file.substring(file.indexOf("filename=\"") + 10);
				upFileName = upFileName.substring(0, upFileName.indexOf("\n"));
				upFileName = upFileName.substring(upFileName.lastIndexOf("\\") + 1, upFileName.indexOf("\"")); 

				/** 取得数据的分隔字符串 */
				String boundary = contentType.substring(contentType.lastIndexOf("boundary=") + 9, contentType.length()); 
				/** 创建保存路径的文件名 */
				String fileName = ComTools.nowSequence() + upFileName.substring(upFileName.lastIndexOf(".")); 

				int pos; 
				pos = file.indexOf("filename=\""); 
				pos = file.indexOf("\n",pos) + 1; 
				pos = file.indexOf("\n",pos) + 1; 
				pos = file.indexOf("\n",pos) + 1; 
				int boundaryLocation = file.indexOf(boundary, pos) - 4;
				
				/** 取得文件数据的开始的位置 */
				int startPos = file.substring(0, pos).length();
				
				/** 取得文件数据的结束的位置 */
				int endPos = file.substring(boundaryLocation).length();
				
				/** 创建文件的写出类 */
				fileOut = new FileOutputStream(uploadPath + fileName); 
				/** 保存文件的数据 */
				fileOut.write(dataBytes, startPos, (fileSize - endPos - startPos));
				
				htmlHashtable.put("%UPLOAD_FILENAME%", uploadRoot + fileName);
				htmlHashtable.put("%UPLOAD_SUCCESSED%", "true");
			}else{ 
				successMessage = "Data type is not multipart/form-data.";
			}
	
		} catch (Exception e) {
			successMessage = e.getMessage();

		} finally {
			try {
				//close open file
				fileOut.close();
				in.close();
				
				htmlHashtable.put("%DISPLAY_MESSAGE%", successMessage);

				/** 输出WEB页面 */
				output_html = output_path + html_upload;
				/** 设置显示页面/字符集属性 */
				OutHTML outHtml = new OutHTML(response, strLanguage);
				outHtml.outputHtml(output_html, htmlHashtable, rsBundle);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Process the HTTP Get request
	 * 
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @throws ServletException,
	 *             IOException
	 * @author fulin
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/** 显示页面 */
		String output_html = null;
		/** 客户端的语言 */
		String strLanguage = null;
		/** 设置页面显示项Hashtable */
		Hashtable htmlHashtable = new Hashtable();
		/** 页面显示信息资源表 */
		ResourceBundle rsBundle = null;

		try {
			/** 客户端的语言 */
			strLanguage = request.getHeader("Accept-Language");
			/** 根据信息文件名取得信息资源表 */
			rsBundle = PropResource.getResource(props_file, strLanguage);
			/** 国际字符表示符(识别符)转换 */
			strLanguage = ComTools.languageConver(strLanguage);

			htmlHashtable.put("%DISPLAY_MESSAGE%", "");
			
		} catch (Exception ex) {
			/** 错误处理输出页面的文件名 */
			htmlHashtable.put("%DISPLAY_MESSAGE%", ex.toString());
			
		} finally {
			try {
				/** 输出WEB页面 */
				output_html = output_path + html_upload;
				/** 设置显示页面/字符集属性 */
				OutHTML outHtml = new OutHTML(response, strLanguage);
				outHtml.outputHtml(output_html, htmlHashtable, rsBundle);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 释放
	 */
	public void destroy() {
		/** 调用父类的方法 */
		super.destroy();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值