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

📄 smartupload.java

📁 实现图书管理
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package mypkg.jspsmart.upload;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

/**
 * The object which perfoms the upload. date: 11 Jul 2000
 * 
 * @author jimshen
 * 
 */
public class SmartUpload {
	protected byte binArray[];

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	protected ServletContext application;

	private int totalBytes;

	private int currentIndex;

	private int startData;

	private int endData;

	private String boundary;

	private long totalMaxFileSize;

	private long maxFileSize;

	private Vector deniedFilesList;

	private Vector allowedFilesList;

	private boolean denyPhysicalPath;

	private String contentDisposition;

	private Files files;

	private Request formRequest;

	private String[] fileNames;

	public static final int SAVE_AUTO = 0;

	public static final int SAVE_VIRTUAL = 1;

	public static final int SAVE_PHYSICAL = 2;

	public SmartUpload() {
		totalBytes = 0;
		currentIndex = 0;
		startData = 0;
		endData = 0;
		boundary = "";
		totalMaxFileSize = 0L;
		maxFileSize = 0L;
		deniedFilesList = new Vector();
		allowedFilesList = new Vector();
		denyPhysicalPath = false;
		contentDisposition = "";
		files = new Files();
		formRequest = new Request();
	}

	/**
	 * @deprecated Since Version 2.1 of jspSmartUpload, use
	 *             initialize(javax.servlet.ServletConfig,
	 *             javax.servlet.http.HttpServletRequest,
	 *             javax.servlet.http.HttpServletResponse) instead.
	 * 
	 * init Initialize the object with the context configuration. This method
	 * always must be called in first.
	 * @param config
	 *            the config object
	 * 
	 */
	public final void init(ServletConfig config) throws ServletException {
		application = config.getServletContext();
	}

	/**
	 * @deprecated Since Version 2.1 of jspSmartUpload, use
	 *             initialize(javax.servlet.ServletConfig,
	 *             javax.servlet.http.HttpServletRequest,
	 *             javax.servlet.http.HttpServletResponse) instead.
	 * 
	 * service Initialize the object with the required Servlet objects. This
	 * method always must be called after the init() method.
	 * @param request
	 *            the request object
	 * @param response
	 *            the response object
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.request = request;
		this.response = response;
	}

	/**
	 * Initialize the object with implicits objects. This method always must be
	 * called in first. This method is meant to be used when the component is
	 * called from a servlet (not a JSP page).
	 * 
	 * @param config
	 *            The application object
	 * @param request
	 *            The request object
	 * @param response
	 *            The response object
	 * @throws ServletException
	 */
	public final void initialize(ServletConfig config,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		application = config.getServletContext();
		this.request = request;
		this.response = response;
	}

	/**
	 * Initialize the object with implicits objects. This method always must be
	 * called in first.
	 * 
	 * @param pageContext
	 *            The pageContext object
	 * @throws ServletException
	 */
	public final void initialize(PageContext pageContext)
			throws ServletException {
		application = pageContext.getServletContext();
		request = (HttpServletRequest) pageContext.getRequest();
		response = (HttpServletResponse) pageContext.getResponse();
	}

	/**
	 * @deprecated initialize(javax.servlet.ServletConfig,
	 *             javax.servlet.http.HttpServletRequest,
	 *             javax.servlet.http.HttpServletResponse) instead.
	 * 
	 * Initialize the object with implicits objects. This method always must be
	 * called in first.
	 * 
	 * @param application
	 *            The application object
	 * @param session
	 *            The session object
	 * @param request
	 *            The request object
	 * @param response
	 *            The response object
	 * @param out
	 *            The out object
	 * @throws ServletException
	 */
	public final void initialize(ServletContext application,
			HttpSession session, HttpServletRequest request,
			HttpServletResponse response, JspWriter out)
			throws ServletException {
		this.application = application;
		this.request = request;
		this.response = response;
	}

	/**
	 * upload Uploads data from the form
	 * 
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 */
	public void upload() throws ServletException, IOException,
			SmartUploadException {
		int i = 0;
		boolean flag1 = false;
		long l = 0L;
		String s4 = "";
		String s5 = "";
		String s6 = "";
		String s7 = "";
		String s8 = "";
		String s9 = "";
		String s10 = "";
		totalBytes = request.getContentLength();
		binArray = new byte[totalBytes];
		int j;
		for (; i < totalBytes; i += j) {
			try {
				request.getInputStream();
				j = request.getInputStream().read(binArray, i, totalBytes - i);
			} catch (Exception exception) {
				throw new SmartUploadException("Unable to upload.");
			}
		}

		for (; !flag1 && currentIndex < totalBytes; currentIndex++) {
			if (binArray[currentIndex] == 13) {
				flag1 = true;
			} else {
				boundary = boundary + (char) binArray[currentIndex];

			}
		}
		if (currentIndex == 1) {
			return;
		}
		for (currentIndex++; currentIndex < totalBytes; currentIndex = currentIndex + 2) {
			String s1 = getDataHeader();
			currentIndex = currentIndex + 2;
			boolean flag3 = s1.indexOf("filename") > 0;
			String s3 = getDataFieldValue(s1, "name");
			if (flag3) {
				s6 = getDataFieldValue(s1, "filename");
				s4 = getFileName(s6);
				s5 = getFileExt(s4);
				s7 = getContentType(s1);
				s8 = getContentDisp(s1);
				s9 = getTypeMIME(s7);
				s10 = getSubTypeMIME(s7);
			}
			getDataSection();
			if (flag3 && s4.length() > 0) {
				if (deniedFilesList.contains(s5)) {
					throw new SecurityException(
							"The extension of the file is denied to be uploaded (1015).");
				}
				if (!allowedFilesList.isEmpty()
						&& !allowedFilesList.contains(s5)) {
					throw new SecurityException(
							"The extension of the file is not allowed to be uploaded (1010).");
				}
				if (maxFileSize > 0L
						&& (long) ((endData - startData) + 1) > maxFileSize) {
					throw new SecurityException(
							"Size exceeded for this file : " + s4 + " (1105).");
				}
				l += (endData - startData) + 1;
				if (totalMaxFileSize > 0L && l > totalMaxFileSize) {
					throw new SecurityException(
							"Total File Size exceeded (1110).");
				}
			}
			if (flag3) {
				File file = new File();
				file.setParent(this);
				file.setFieldName(s3);
				file.setFileName(s4);
				file.setFileExt(s5);
				file.setFilePathName(s6);
				file.setIsMissing(s6.length() == 0);
				file.setContentType(s7);
				file.setContentDisp(s8);
				file.setTypeMIME(s9);
				file.setSubTypeMIME(s10);
				if (s7.indexOf("application/x-macbinary") > 0) {
					startData = startData + 128;
				}
				file.setSize((endData - startData) + 1);
				file.setStartData(startData);
				file.setEndData(endData);
				files.addFile(file);
			} else {
				String s11 = new String(binArray, startData,
						(endData - startData) + 1);
				formRequest.putParameter(s3, s11);
			}
			if ((char) binArray[currentIndex + 1] == '-') {
				break;
			}
		}
	}

	/**
	 * Saves all the uploaded files in the specified destination
	 * 
	 * @param destPathName
	 *            The destination path
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 */
	public int save(String destPathName) throws ServletException, IOException,
			SmartUploadException {
		return save(destPathName, 0);
	}

	/**
	 * Saves all the uploaded files in the specified destination
	 * 
	 * @param destPathName
	 *            The destination path
	 * @param option
	 *            SAVEAS_AUTO : The method save in a virtual if it exists else
	 *            consider the path as a physical if the porperty
	 *            denyPhysicalPath is false. SAVEAS_VIRTUAL: The method save the
	 *            file only if the path is a virtual path. SAVEAS_PHYSICAL: The
	 *            method save the file only if the path is a physical path.
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 */
	public int save(String destPathName, int option) throws ServletException,
			IOException, SmartUploadException {
		int j = 0;
		if (destPathName == null) {
			destPathName = application.getRealPath("/");
		}
		if (destPathName.indexOf("/") != -1) {
			if (destPathName.charAt(destPathName.length() - 1) != '/') {
				destPathName = destPathName + "/";
			}
		} else {
			if (destPathName.charAt(destPathName.length() - 1) != '\\') {
				destPathName = destPathName + "\\";
			}
		}
		fileNames = new String[files.getCount()];
		for (int k = 0; k < files.getCount(); k++) {
			if (!files.getFile(k).isMissing()) {
				files.getFile(k).saveAs(
						destPathName + files.getFile(k).getFileName(), option);
				fileNames[j] = destPathName + files.getFile(k).getFileName();
				j++;
			}
		}

		return j;
	}

	public String[] getFileNames() {
		// Method may expose internal representation by returning array
		// Returning an array value stored in one of the object's fields exposes
		// the internal representation of the object.? For classes shared by
		// other untrusted classes, this could potentially be a security issue.?
		// Returning a new copy of the array is better approach in many
		// situations.
		String[] vFileNames = new String[fileNames.length];
		System.arraycopy(fileNames, 0, vFileNames, 0, fileNames.length);
		return vFileNames;
	}

	/**
	 * Returns the total size of data uploaded
	 * 
	 * @return the total size of data uploaded
	 */
	public int getSize() {
		return totalBytes;
	}

	/**
	 * Returns the byte corresponding to the table index containing the
	 * transmitted data
	 * 
	 * @param index
	 *            index of the table
	 * @return
	 */
	public byte getBinaryData(int index) {
		byte byte0;
		try {
			byte0 = binArray[index];
		} catch (Exception exception) {
			throw new ArrayIndexOutOfBoundsException(
					"Index out of range (1005).");
		}
		return byte0;
	}

	/**
	 * Returns the collection of the uploaded files
	 * 
	 * @return the collection of the uploaded files
	 */
	public Files getFiles() {
		return files;
	}

	/**
	 * Returns the request object
	 * 
	 * @return the request object
	 */
	public Request getRequest() {
		return formRequest;
	}

	/**
	 * Downloads a file
	 * 
	 * @param sourceFilePathName
	 *            The full path to the file to download
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 */
	public void downloadFile(String sourceFilePathName)
			throws ServletException, IOException, SmartUploadException {
		downloadFile(sourceFilePathName, null, null);
	}

	/**
	 * Downloads a file
	 * 
	 * @param sourceFilePathName
	 *            The full path to the file to download
	 * @param contentType
	 *            the content type
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 * @throws SmartUploadException
	 */
	public void downloadFile(String sourceFilePathName, String contentType)
			throws ServletException, IOException, SmartUploadException,
			SmartUploadException {
		downloadFile(sourceFilePathName, contentType, null);
	}

	/**
	 * Downloads a file
	 * 
	 * @param sourceFilePathName
	 *            The full path to the file to download
	 * @param contentType
	 *            the content type
	 * @param destFilename
	 *            the suggested file name
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 */
	public void downloadFile(String sourceFilePathName, String contentType,
			String destFilename) throws ServletException, IOException,
			SmartUploadException {
		downloadFile(sourceFilePathName, contentType, destFilename, 65000);
	}

	/**
	 * Downloads a file
	 * 
	 * @param sourceFilePathName
	 *            The full path to the file to download
	 * @param contentType
	 *            the content type
	 * @param destFilename
	 *            the suggested file name
	 * @param blockSize
	 * @throws ServletException
	 * @throws IOException
	 * @throws SmartUploadException
	 */
	public void downloadFile(String sourceFilePathName, String contentType,
			String destFilename, int blockSize) throws ServletException,
			IOException, SmartUploadException {
		if (sourceFilePathName == null) {
			throw new IllegalArgumentException("File '" + sourceFilePathName
					+ "' not found (1040).");
		}
		if (sourceFilePathName.equals("")) {
			throw new IllegalArgumentException("File '" + sourceFilePathName
					+ "' not found (1040).");
		}
		if (!isVirtual(sourceFilePathName) && denyPhysicalPath) {
			throw new SecurityException("Physical path is denied (1035).");
		}
		if (isVirtual(sourceFilePathName)) {
			sourceFilePathName = application.getRealPath(sourceFilePathName);
		}
		java.io.File file = new java.io.File(sourceFilePathName);
		FileInputStream fileinputstream = new FileInputStream(file);
		long length = file.length();
		// boolean flag = false;
		int k = 0;
		byte abyte0[] = new byte[blockSize];
		if (contentType == null) {
			response.setContentType("application/x-msdownload");
		} else {
			if (contentType.length() == 0) {
				response.setContentType("application/x-msdownload");
			} else {
				response.setContentType(contentType);
			}
		}
		response.setContentLength((int) length);
		contentDisposition = contentDisposition != null ? contentDisposition
				: "attachment;";
		if (destFilename == null) {
			response.setHeader("Content-Disposition", contentDisposition
					+ " filename="
					+ encodeString(getFileName(sourceFilePathName)));
		} else {
			if (destFilename.length() == 0) {
				response.setHeader("Content-Disposition", contentDisposition);
			} else {
				response.setHeader("Content-Disposition", contentDisposition
						+ " filename=" + encodeString(destFilename));
			}
		}
		while ((long) k < length) {
			int j = fileinputstream.read(abyte0, 0, blockSize);
			k += j;

⌨️ 快捷键说明

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