Thoroughly get Java file upload (transfer)

xiaoxiao2021-03-06  114

Java's documents have been spread all over a matter of concern, and there are several NBs provide this feature.

The most important thing is three (I know these three), one is the earlier JSPSmartupload, the other is the CommonupLoad of the family, and one is ORELLY.

The more than the top two, the total feeling is that JSPSmartup is more flexible, function is stronger (a little bit), but now there is no maintenance, and you can't download, especially it is uploaded. Put it in memory, so the size of the upload file and the memory have a relationship. Although CommonupLoad does not provide a lot of APIs, it has a more flexible, it will write uploaded the uploaded file in the process, so uploaded size is only bandwidth There is a relationship, I try the biggest upload file size is 700m, of course, local test:>

There is also a Chinese issue that is uploaded in Linux / UNIX system, I have some solutions in the code below.

Below is the upload code of the first two ways:

Try {// Take the session user oidint pid = userinfo.getUserid (); string sys_user_id = string.valueof (pid); // Take the parameter value of the init configuration file string sitephysicalPath = (STRING) init.getObject ("SitephysicalPath"); String Savedir = (String) Init.getObject ("InfoupLoadDir"); String Tempdir = (String) Init.getObject ("InfoupLoadDir"); String FileMEMO = ""; // File Description String FileName = NULL; // Store to Database File name string savename = null; // Store the local file name string filepath = null; // Store SAVEPATH = null; // Stores LONG FILESIZE = 0; // File Size INT MAXPOSTSIZE = -1; INT DINFO_UPLOAD_ID = -1;%> <% // Initialization MySmartupload.initialize (PageContext); // Upload file mysmartupload.upload (); // Loop acquire all upload file for (INT i = 0 i

} Catch (Exception E) {Savename = "";} // acquired file size filesize = file.getsize (); // Storage path string sql_id = "select s_info_upload.nextVal as seqid from dual"; try {statement stmt = con .createStatement (); ResultSet rst = stmt.executeQuery (sql_id); while (rst.next ()) {dinfo_upload_id = rst.getInt ( "seqid");}} catch (SQLException sqle) {return;} filePath = sitePhysicalPath saveDir Integer.toString (dinfo_upload_id) saveName; savePath = saveDir Integer.toString (dinfo_upload_id) saveName; // file to the local storage file.saveAs (filePath); // file stored in a database switch (i) {case 0 : FileMemo = (String) mysmartupload.getRequest (). getParameter ("Memo1"); Break; Case 1: FileMemo = (String) mysmartupload.getRequest (). getParameter ("Memo2"); break; case 2: filememo = String) mySmartUpload.getRequest () getParameter ( "memo3"); break; case 3:. fileMemo = (String) mySmartUpload.getRequest () getParameter ( "memo4"); break; case 4:. fileMemo = (String) mySmartUpload. getRequest (). getParameter ("Memo5"); Break; Default: FileMemo = ""

String sql = "INSERT INTO info_upload (info_upload_id, sys_user_id, file_size, file_path, utime, deleted)" "VALUES (" Integer.toString (dinfo_upload_id) "," sys_user_id "," fileSize ", '" SavePath "', sysdate, 0)"; SQLCMD CMD = New SQLCMD (Con, SQL); // System.out.Println (SQL); java.sql.preparedState pstmt = null; java.sql.Statement Stmt = null; // fileName = fileName.substring (0, fileName.indexOf () "."); String sql_cn = "UPDATE info_upload SET file_name = ?, file_memo = WHERE info_upload_id =??"; java.io.ByteArrayInputStream bais_name = new java.io.ByteArrayInputStream (fileName.getBytes ( "ISO-8859-1")); java.io.InputStreamReader isr_name = new java.io.InputStreamReader ((InputStream) bais_name, "GBK"); java.io.ByteArrayInputStream bais_memo = New java.io.byteArrayInputStream (FileMemo.getBytes ("GBK")); java.io.inputstreamReader isr_memo = new java.io.inputstreamReader (InputStream) Bais_MEMO, "GBK");

Try {stmt = con.createstatement (); stmt.getConnection (). setAutocommit (false);

pstmt = con.prepareStatement (sql_cn); pstmt.setCharacterStream (1, isr_name, fileName.length ()); pstmt.setCharacterStream (2, isr_memo, fileMemo.length ()); pstmt.setInt (3, dinfo_upload_id);

//System.out.println (SQL_CN);

Pstmt.execute (); stmt.executeUpdate ("commit");

} catCH (Exception Exce) {system.ord.Println (Exce); stmt.executeUpdate ("rollback");}}}} catch (Exception E) {}

The above is a JSPSMART, if you want other ways, please download all source code. //UPLOAD_FILEUPLOAD.JSP

<% @ include file = "../../backgeneral.jsp" %>% @ Contenttype =" text / html; charset = GBK "%> <% @ page import = "org.apache.commons.fileupload. *"%> <% try {//request.setcharacterencoding ("GBK ";/ 取 session user oid int pid = userInfo.getUserId (); String sys_user_id = String.valueOf (pid); // init parameter takes the value of the configuration file String sitePhysicalPath = (String) init.getObject ( "SitePhysicalPath"); String saveDir = (String INIT.GETOBJECT ("InfoupLoadDir"); String Tempdir = (String) Init.getObject ("InfouPloadDir"); String FileMemo = ""; // File Description String FileName = NULL; // Store String Savename = NULL; // Stores the local file name string filepath = null; // Store to the local file path string savePath = null; // Stores the file path for the database LONG FILESIZE = 0; // File size int maxpostsize = - 1; int DINFO_UPLOAD_ID = -1;%> <% diskfileupload df = new diskfileupload (); // Set upload file size DF.setSizeMax (MAXPOSTSIZE); // Set the temporary directory DF.SetRepositoryPath (SitephysicalPath Tempdir); / / Get a request information List IT EMS = DF.Parsequest (Request); iterator it = items.iterator (); int Temp = 0; fileItem TempItem = NULL;

While (iter.hasnext ()) {temp ; fileItem item = (fileItem) iter.next (); if (item.isformfield ()) // acquisition file Description Information {fileMemo = Item.getstring ("GBK");} ELSE {// get uploaded file information filename = (string) item.getname (); try {filename = filename.substring (filename.lastindexof ("//") 1); filename = filename.substring (filename.lastIndexof) "/") 1);} catch (exception e) {system.out.println (e);} filesis = item.getsize (); tempItem = item;} if (Temp == 2 && filesis! = 0) {// Each two ITER stores an upload file

// get info_title_id String SQL_ID = "select S_INFO_UPLOAD.nextval as seqid from dual"; try {java.sql.Statement stmt = con.createStatement (); java.sql.ResultSet rst = stmt.executeQuery (SQL_ID); while (rst .next ()) {DINFO_UPLOAD_ID = RST.GETINT ("seqid");}

} Catch (SQLEXCEPTION E1) {return;} // acquire file extension try {savename = filename.substring ("."));} Catch (Exception Exc) {savename = ""

filePath = sitePhysicalPath saveDir Integer.toString (dinfo_upload_id) saveName; // store file java.io.File uploadFile = new java.io.File (filePath); tempItem.write (uploadFile); / * try {FileOutputStream fos = New fileoutputstream (filepath); inputStream is = tempItem.GetinputStream (); byte [] b = new byte [1024]; int Nread; long per = 0; double percent = 0; while ((NREAD = is.read (b, 0, 1024))> 0) {Fos.Write (B, 0, NREAD); percent = NREAD; percent = (double) per / filesis;

Session.SetaTribute ("Percent", Double.Tostring (Percent) .Substring (2, 4)); session.settribute ("filename", filename);} is.close (); fos.close ();} catch Exception e) {System.out.println (e);} * / savePath = saveDir Integer.toString (dinfo_upload_id) saveName; / * / store database String sql = "INSERT INTO info_upload (info_upload_id, sys_user_id, file_name, file_memo, FILE_SIZE, FILE_PATH, UTIME, DELETED " " VALUES (" Integer.Tostring (DINFO_UPLOAD_ID) ", " SYS_USER_ID ", '" FileName ",' " FileMemo ", " FileSize ", '" savePath "', SYSDATE, 0)"; sqlcmd cmd = new sqlcmd (con, sql); * / String sql = "INSERT INTO info_upload (info_upload_id, sys_user_id, file_size, file_path, utime, deleted)" "VALUES (" Integer.Tostring (DINFO_UPLOAD_ID) "," SYS_USER_ID "," FileSize ", '" SavePath "', sysdate, 0)"; SQLCMD CMD = New SQLCMD (CON, SQL ); // system .out.println (SQL); java.sql.preparedStatement pstmt = null; java.sql.Statement Stmt = null; // filename = filename.substring (0, filename.indexof (".")); string sql_cn = " UPDATE info_upload SET file_name = ?, file_memo = WHERE info_upload_id =?? "; java.io.ByteArrayInputStream bais_name = new java.io.ByteArrayInputStream (fileName.getBytes (" ISO-8859-1 ")); java.io.InputStreamReader isr_name =

new java.io.InputStreamReader ((InputStream) bais_name, "GBK"); java.io.ByteArrayInputStream bais_memo = new java.io.ByteArrayInputStream (fileMemo.getBytes ( "GBK")); java.io.InputStreamReader isr_memo = new java .io.inputstreamReader (InputStream) BAIS_MEMO, "GBK"); try {stmt = con.createstatement (); stmt.getConnection (). setAutocommit (false);

pstmt = con.prepareStatement (sql_cn); pstmt.setCharacterStream (1, isr_name, fileName.length ()); pstmt.setCharacterStream (2, isr_memo, fileMemo.length ()); pstmt.setInt (3, dinfo_upload_id);

//System.out.println (SQL_CN);

Pstmt.execute (); stmt.executeUpdate ("commit");

} catch (exception exce) {system.out.println; stmt.executeUpdate ("rollback");}

Temp = 0;} else if (Temp == 2 && filesis == 0) {TEMP = 0;

} //Session.setttribute ("Percent ", "om";}}}} }.out.println (ex);} response.sendredirect ("list.jsp");

%> // Upload_jspsmart.jsp

<% @ include file = "../../backGeneral.jsp" %><%@Page language =" java "import =" java.usu1 *, java.sql. *, java.io. * "% > <% @ page language = "java" import = "com.jspsmart.upload. *"%> <% @ page language = "java" import = "com.ges.hbgov. *"%> < % // system.out.println ("Page =" (String) session.gettribute ("sys_user_id")); if (! Userinfo.request (request)) {%>