⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileupload.java

📁 运用hibernate技术 实现的留言板
💻 JAVA
字号:
/**
 * 
 */
package com.tiandinet.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.Hashtable;
import java.util.Random;
import java.util.Calendar;
import java.util.Date;

/**
 * The File Upload function.
 * @author Meng Yang
 * @version 1.0.1
 */
public class FileUpload {
	
	// store all fields in the form
	// if if a file, there will be store a type of UploadedFile
	private Hashtable fields;
	
	// the types of file
	private String allowExtendName = ".gif.jpg.jpeg.zip.rar";
	
	// location to store
	private String savePath = ".";
	
	// max size
	private long size = 100 * 1024;
	
	// absolute path of current context
	public String absolutePath = "";	
	private ServletInputStream inStream = null;
	private byte[] b = new byte[4096];
	private Random rand = new Random();

	/**
	 * 
	 */
	public FileUpload() {
		this.fields = new Hashtable();
	}
	
	public Hashtable getFields() {
		return this.fields;
	}
	
	public String getAllowExtendName() {
		return this.allowExtendName;
	}
	public void setAllowExtendName(String extName) {
		this.allowExtendName = extName;
	}
	
	public String getSavePath() {
		return this.savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	public long getSize() {
		return this.size;
	}
	public void setSize(long s) {
		this.size = s;
	}
	
	/**
	 * parse the request stream
	 * @param request
	 */
	public void parseRequest(ServletContext context, HttpServletRequest request) 
					throws IOException {
		// init the path
		String path = context.getRealPath("/");
		path = path.replace('\\', '/');
		int length = path.length();

		if (path.charAt(length - 1) == '/') {
			path = path.substring(0, length - 1);
		}
		this.absolutePath = path;
		
		// parse the request
		this.inStream = request.getInputStream();

		int readLength = 0;
		int offset = 0;
		String str = "";
		int a = 0;
		int b = 0;
		String formName = "";
		String formTextName = "";

		while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) // readLength?????b?????-1???????
		{
			str = new String(this.b, 0, readLength);

			// file
			if ((offset = str.indexOf("filename=\"")) != -1) {
				FileField fField = new FileField();
				
				// get the field name
				a = str.indexOf("name=\"");
				formName = str.substring(a + 6);
				b = formName.indexOf("\"");
				formName = formName.substring(0, b);
				fField.fieldName = formName;

				// get the client file name
				str = str.substring(offset + 10);
				b = str.indexOf("\"");
				str = str.substring(0, b);
				if (str.equals("")) {
					fField.status = false;
					this.fields.put(fField.fieldName, fField);
					continue;
				}
				fField.clientFileName = str;

				// get the extend name
				a = fField.clientFileName.lastIndexOf(".");
				fField.extendName = fField.clientFileName.substring(a + 1);

				// check extend name
				if (this.checkFileExt(fField)) {
					this.doUpload(fField);
					this.fields.put(fField.fieldName, fField);
				}
				else {
					fField.status = false;
					fField.message = "Failed to upload file: Invalid extend name.";
					this.fields.put(fField.fieldName, fField);
					continue;
				}
			}
			// common field
			else if ((offset = str.indexOf("name=\"")) != -1) {
				CommonField cField = new CommonField();
				// get the field name
				formTextName = str.substring(offset + 6);
				a = formTextName.indexOf("\"");
				formTextName = formTextName.substring(0, a);
				cField.fieldName = formTextName;
				
				this.getInputValue(cField);

				this.fields.put(cField.fieldName, cField);
			}
			else {
				continue;
			}
		}
	}
	
	// check extend name
	public boolean checkFileExt(FileField fField) {
		if ((this.allowExtendName.indexOf(fField.extendName)) != -1) {
			return true;
		}
		else {
			return false;
		}
	}

	// upload file
	public boolean doUpload(FileField fField) {
		// get the current time
		Date currentDate = new Date();
		this.rand.setSeed(currentDate.getTime());
		int randNum = rand.nextInt(100);
		
		Calendar cal = Calendar.getInstance();
		int year    = cal.get(Calendar.YEAR);
		int month   = cal.get(Calendar.MONTH)+1;
		int day     = cal.get(Calendar.DATE);
		int hour24  = cal.get(Calendar.HOUR_OF_DAY);
		int minute  = cal.get(Calendar.MINUTE);
		int second  = cal.get(Calendar.SECOND);
		int msecond = cal.get(Calendar.MILLISECOND);
		
		String tY,tMon,tD,tH24,tMin,tS, tMsecond;
		
		tY   = String.valueOf(year);
		tMon = String.valueOf(month);
		tD   = String.valueOf(day);
		tH24 = String.valueOf(hour24);
		tMin = String.valueOf(minute);
		tS   = String.valueOf(second);
		tMsecond = String.valueOf(msecond);
		
		tMon = (tMon.length() == 1)?("0"+tMon):tMon;
		tD   = (tD.length() == 1)?("0"+tD):tD;
		tH24 = (tH24.length() == 1)?("0"+tH24):tH24;
		tMin = (tMin.length() == 1)?("0"+tMin):tMin;
		tS   = (tS.length() == 1)?("0"+tS):tS;
		
		String timeString = tY + tMon + tD + tH24 + tMin + tS + "." + tMsecond;
		
		String objFileName = timeString	+ "_" + Integer.toString(randNum);
		try {
			fField.objectFileName = objFileName + "_bak." + fField.extendName;

			File objFile = new File(this.absolutePath + "/" + this.savePath,
					fField.objectFileName);
			
			// if the file exists
			if (objFile.exists()) {
				// call self to generate the new file name
				this.doUpload(fField);
			}
			else {
				objFile.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(objFile);
			BufferedOutputStream bos = new BufferedOutputStream(fos);

			int readLength = 0;
			int offset = 0;
			String str = "";
			
			// the readed size, to check the file size
			long readSize = 0L;

			// move the offset to the line Content-Type:
			while ((readLength = this.inStream.readLine(this.b, 0,
					this.b.length)) != -1) {
				str = new String(this.b, 0, readLength);
				if (str.indexOf("Content-Type:") != -1) {
					break;
				}
			}

			// read blank line
			this.inStream.readLine(this.b, 0, this.b.length);

			while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) {
				// check the file has been read
				str = new String(this.b, 0, readLength);
				if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45
						&& this.b[3] == 45 && this.b[4] == 45) {
					break;
				}

				// write file
				bos.write(this.b, 0, readLength);

				readSize += readLength;

				if (readSize > this.size) {
					fField.message = "Failed to upload file: Invalid file size.";
					fField.status = false;
					break;
				}
			}

			if (fField.status)
			{
				bos.flush();
				bos.close();

				// read the uploaded file content, add throw off the "\n"
				int fileLength = (int) (objFile.length());
				byte[] bb = new byte[fileLength - 2];
				FileInputStream fis = new FileInputStream(objFile);
				BufferedInputStream bis = new BufferedInputStream(fis);
				bis.read(bb, 0, (fileLength - 2));
				fis.close();
				bis.close();

				fField.objectFileName = objFileName + "." + fField.extendName;
				File ok_file = new File(this.absolutePath + "/" + this.savePath,
						fField.objectFileName);
				ok_file.createNewFile();
				BufferedOutputStream bos_ok = new BufferedOutputStream(
						new FileOutputStream(ok_file));
				bos_ok.write(bb);
				bos_ok.close();
				objFile.delete();

				fField.status = true;
				return true;
			}
			else {
				bos.flush();
				bos.close();
				File delFile = new File(this.absolutePath + "/" + this.savePath,
						fField.objectFileName);
				delFile.delete();
				fField.status = false;
				return false;
			}

		} catch (Exception e) {
			fField.status = false;
			fField.message = "Failed to upload file: " + e.toString();
			return false;
		}

	}
	
	// get the value of common field
	public boolean getInputValue(CommonField cField) {
		String str = "";
		int readLength = 0;
		try {
			this.inStream.readLine(this.b, 0, this.b.length);

			StringBuffer formTextValue = new StringBuffer();

			// get the value
			while ((readLength = this.inStream.readLine(this.b, 0,
					this.b.length)) != -1) {
				str = new String(this.b, 0, readLength);
				if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45
						&& this.b[3] == 45 && this.b[4] == 45) {
					break;
				}
				formTextValue.append(str);
			}

			str = formTextValue.toString();
			cField.fieldValue = str.substring(0, str.length() - 2);
			cField.status = true;
			return true;
		} catch (Exception e) {
			cField.fieldValue = null;
			cField.status = false;
			return false;
		}
	}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -