자바 응용 모음 집 4: 대상 업로드 진행 표시 줄 저장

전재 출처 를 밝 혀 주 십시오: http://renjie120.iteye.com/
 
fileupload 를 사용 하여 문 서 를 업로드 하고 blob 필드 에 저장 하 며 업로드 하 는 과정 에서 진 도 를 표시 합 니 다.
<form name="uploadform" id="uploadform" method="POST"
			action="upload.action" ENCTYPE="multipart/form-data" target="hidden">
			    1:
			<input type="file" id="filename1" name="filename1"
				onchange="setflag(true);"
				onblur="getFileSize('filename1','fileinf1');" name="filename">
			<div id="fileinf1" style="display: none"></div>
			<br>
			    2:
			<input type="file" id="filename2" name="filename2"
				onchange="setflag(true);"
				onblur="getFileSize('filename2','fileinf2');" name="sheet">
			<div id="fileinf2" style="display: none"></div>
			<br>
			    3:
			<input type="file" id="filename3" name="filename3"
				onchange="setflag(true);"
				onblur="getFileSize('filename3','fileinf3');" name="sheet">
			<div id="fileinf3" style="display: none"></div>
			<br>
			    4:
			<input type="file" accept="image/gif" name="filename4" id="filename4"
				onchange="setflag(true);"
				onblur="getFileSize('filename4','fileinf4');" name="sheet">
			<div id="fileinf4" style="display: none"></div>
			<br>
			<button onclick="upload();">
				  
			</button>
		</form>

 action:
package upload;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lsframe.mvc.ActionContext;

public class NewUpload {
	private Log log = LogFactory.getLog("logger");

	private long maxsize = 1000000000;
	UploadDao dao = new UploadDao();

	public String execute() throws Exception {
		ActionContext context = ActionContext.getContext();
		final HttpServletRequest request = context.getHttpServletRequest();

		DiskFileItemFactory factory = new DiskFileItemFactory();
		//                 
		factory.setSizeThreshold(10000);
		//                   !
		factory.setRepository(new File("c:\\temp"));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxsize);
		
		//              .


		ProgressListener progressListener = new ProgressListener() {
			private long megaBytes = -1;
			public void update(long pBytesRead, long pContentLength, int pItems) {
				System.out.println("We are currently reading item " + pItems);
				long mBytes = pBytesRead / 1000000;
				System.out.println(mBytes);
				if (megaBytes == mBytes) {
					return;
				}
				System.out.println(" " + pItems);
				megaBytes = mBytes;
				System.out.println("We are currently reading item " + pItems);
				if (pContentLength == -1) {
					System.out.println("So far, " + pBytesRead
							+ " bytes have been read.");
				} else {
					System.out.println("So far, " + pBytesRead + " of "
							+ pContentLength + " bytes have been read.");
				}
			}
		};
		//            .
		upload.setProgressListener(progressListener);
		FileItem fi = null;
		String fileName = "";
		int endtag = 0;
		String shortName = "";
		Iterator it =  null;
		//                               !!


		final List fileItems = upload.parseRequest(request);
		try {
			it = fileItems.iterator();
			while (it.hasNext()) {
				fi = (FileItem) it.next();
				fileName = fi.getName();
				endtag = fileName.lastIndexOf("\\");
				if (endtag == -1) {
					continue;
				}
				shortName = fileName.substring(endtag + 1);
				//                
				UploadVO file = new UploadVO(shortName,fi.get(),(int)fi.getSize());
				file = dao.preSaveBlob(file);
				dao.insertIntoBlob(file);				
			}
			request.setAttribute("aaa", "  OK!");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("aaa", "    ,        "
					+ new Long(maxsize).toString() + "  !");
		}
		return "success";
	}

	/**
	 *          ,      json  ..
	 * 
	 * @return
	 */
	public String getUploadProgress() {
		return null;
	}

	/**
	 *          
	 * 
	 * @param fileName
	 * @return
	 */
	public String getMaxFileSize() {
		String str = new Long(maxsize).toString();
		return str;
	}

}

 
blob 필드 에 저장 하려 면 먼저 빈 blob 필드 를 삽입 하고 데이터베이스 에 있 는 이 필드 를 io 흐름 으로 기록 해 야 합 니 다.
package upload;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import oracle.sql.BLOB;

import com.lsframe.jdbc.DBPoolManager;
import com.lsframe.jdbc.DataBase;

public class UploadDao {
	private DataBase dao = new DataBase();

	/**
	 *               ,          
	 * @return
	 * @throws SQLException 
	 */
	public int insertIntoBlob(UploadVO file) throws SQLException {
		String saveSql = "SELECT BLOB_CONTENT FROM TEST_BLOB_T WHERE BLOB_ID = ? FOR UPDATE";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rest = null;
		boolean ans = false;
		conn = DBPoolManager.getInstance().getDBConn();  
		try {
			conn.setAutoCommit(false);
			pstmt = conn.prepareStatement(saveSql);
			pstmt.setString(1, file.getBlobId());
			rest = pstmt.executeQuery();

			if (rest.next()) {
				ans = saveToDatabase((BLOB) rest.getBlob("BLOB_CONTENT"),
						file.getFileContent(), file.getFsize());
			}
			conn.setAutoCommit(true);
		} catch (Exception e) {
			System.out.println("           !
:" + e.getMessage()); } finally { rest.close(); pstmt.close(); conn.close(); } return 0; } /** * blob . * @param blobContent blob * @param fileBody , * @param vSize * @return * @throws IOException */ private boolean saveToDatabase(BLOB blobContent, byte[] fileBody, int vSize) throws IOException { boolean result = false; try { OutputStream outstream = blobContent.getBinaryOutputStream(); outstream.write(fileBody, 0, vSize); outstream.close(); result = true; } catch (SQLException e) { result = false; e.printStackTrace(); } catch (Exception e) { result = false; e.printStackTrace(); } return result; } /** * . * @return */ public UploadVO preSaveBlob(UploadVO file) { String getSeq = "SELECT TESTBLOBSEQ.NEXTVAL FROM DUAL"; String saveSql = "INSERT INTO TEST_BLOB_T(BLOB_CONTENT,BLOB_TIME,BLOB_SIZE,BLOB_NAME,BLOB_ID) VALUES " + "(EMPTY_BLOB(),SYSDATE,?,?,?)"; List argList = new ArrayList(); argList.add(file.getFsize()); argList.add(file.getFileName()); int ans = 0; String seq = ""; try { // seq = dao.queryForString(getSeq); argList.add(seq); // , blob ans = dao.updateRecords(saveSql,argList); file.setBlobId(seq); } catch (Exception e) { System.out.println(" !
:" + e.getMessage()); } return file; } }

 
관련 표 의 구조:
create table TEST_BLOB_T
(
  BLOB_ID      VARCHAR2(30) not null,
  BLOB_SIZE    NUMBER(20,4),
  BLOB_CONTENT BLOB,
  BLOB_TIME    DATE,
  BLOB_NAME    VARCHAR2(50)
)

좋은 웹페이지 즐겨찾기