Java 文件上传的实例详解

Java 文件上传的实例详解

java 文件上传

Java文件上传,介绍几种常用的方法,也是经过本人亲手调试过的

1.jspsmartupload

这个组件用起来是挺方便的,不过就是只适合小文件上传,如果大文件上传的话就不行,查看了一下他的代码,m_totalBytes = m_request.getContentLength(); m_binArray = new byte[m_totalBytes];居然把整个上传文件都读到内存去了,那如果是上传几十M的文件,同时几个用户上传,服务器稳挂,不过如果只是上传5M以内的小文件,这个组件还是挺实用的

下面是源代码:

File类

/*
 * 创建日期 2006-7-29
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.kinstar.issuing.file;
/**
 * @author gongyifeng
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
// Referenced classes of package com.jspsmart.upload:
// SmartUploadException, SmartUpload
public class File{
 private SmartUpload m_parent;
 private int m_startData;
 private int m_endData;
 private int m_size;
 private String m_fieldname;
 private String m_filename;
 private String m_fileExt;
 private String m_filePathName;
 private String m_contentType;
 private String m_contentDisp;
 private String m_typeMime;
 private String m_subTypeMime;
 private String m_contentString;
 private boolean m_isMissing;
 public static final int SAVEAS_AUTO = 0;
 public static final int SAVEAS_VIRTUAL = 1;
 public static final int SAVEAS_PHYSICAL = 2;
 File(){
 m_startData = 0;
 m_endData = 0;
 m_size = 0;
 m_fieldname = new String();
 m_filename = new String();
 m_fileExt = new String();
 m_filePathName = new String();
 m_contentType = new String();
 m_contentDisp = new String();
 m_typeMime = new String();
 m_subTypeMime = new String();
 m_contentString = new String();
 m_isMissing = true;
 }
 public void saveAs(String s) throws IOException, SmartUploadException{
 saveAs(s, 0);
 }
 public void saveAs(String s, int i) throws IOException, SmartUploadException{
 String s1 = new String();
 s1 = m_parent.getPhysicalPath(s, i);
 if(s1 == null)
  throw new IllegalArgumentException("There is no specified destination file (1140).");
 try
 {
  java.io.File file = new java.io.File(s1);
  FileOutputStream fileoutputstream = new FileOutputStream(file);
  fileoutputstream.write(m_parent.m_binArray, m_startData, m_size);
  fileoutputstream.close();
 }
 catch(IOException ioexception)
 {
  throw new SmartUploadException("File can't be saved (1120).");
 }
 }
 public void fileToField(ResultSet resultset, String s) throws ServletException, IOException, SmartUploadException, SQLException{
 long l = 0L;
 int i = 0x10000;
 int j = 0;
 int k = m_startData;
 if(resultset == null)
  throw new IllegalArgumentException("The RecordSet cannot be null (1145).");
 if(s == null)
  throw new IllegalArgumentException("The columnName cannot be null (1150).");
 if(s.length() == 0)
  throw new IllegalArgumentException("The columnName cannot be empty (1155).");
 l = BigInteger.valueOf(m_size).divide(BigInteger.valueOf(i)).longValue();
 j = BigInteger.valueOf(m_size).mod(BigInteger.valueOf(i)).intValue();
 try
 {
  for(int i1 = 1; (long)i1 < l; i1++)
  {
  resultset.updateBinaryStream(s, new ByteArrayInputStream(m_parent.m_binArray, k, i), i);
  k = k != 0 ? k : 1;
  k = i1 * i + m_startData;
  }

  if(j > 0)
  resultset.updateBinaryStream(s, new ByteArrayInputStream(m_parent.m_binArray, k, j), j);
 }catch(SQLException sqlexception){
  byte abyte0[] = new byte[m_size];
  System.arraycopy(m_parent.m_binArray, m_startData, abyte0, 0, m_size);
  resultset.updateBytes(s, abyte0);
 }catch(Exception exception)
 {
  throw new SmartUploadException("Unable to save file in the DataBase (1130).");
 }
 }
 public boolean isMissing(){
 return m_isMissing;
 }

 public String getFieldName(){
 return m_fieldname;
 }

 public String getFileName(){
 DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
 String date = df.format(new Date());

 return date+m_filename;
 }

 public String getFilePathName(){
 return m_filePathName;
 }

 public String getFileExt(){
 return m_fileExt;
 }

 public String getContentType(){
 return m_contentType;
 }

 public String getContentDisp(){
 return m_contentDisp;
 }

 public String getContentString(){
 String s = new String(m_parent.m_binArray, m_startData, m_size);
 return s;
 }

 public String getTypeMIME() throws IOException{
 return m_typeMime;
 }

 public String getSubTypeMIME(){
 return m_subTypeMime;
 }

 public int getSize(){
 return m_size;
 }

 protected int getStartData(){
 return m_startData;
 }

 protected int getEndData(){
 return m_endData;
 }

 protected void setParent(SmartUpload smartupload){
 m_parent = smartupload;
 }

 protected void setStartData(int i){
 m_startData = i;
 }

 protected void setEndData(int i){
 m_endData = i;
 }

 protected void setSize(int i){
 m_size = i;
 }

 protected void setIsMissing(boolean flag){
 m_isMissing = flag;
 }

 protected void setFieldName(String s){
 m_fieldname = s;
 }

 protected void setFileName(String s){
 m_filename = s;
 }

 protected void setFilePathName(String s){
 m_filePathName = s;
 }

 protected void setFileExt(String s){
 m_fileExt = s;
 }

 protected void setContentType(String s){
 m_contentType = s;
 }

 protected void setContentDisp(String s){
 m_contentDisp = s;
 }

 protected void setTypeMIME(String s){
 m_typeMime = s;
 }

 protected void setSubTypeMIME(String s){
 m_subTypeMime = s;
 }

 public byte getBinaryData(int i){
 if(m_startData + i > m_endData)
  throw new ArrayIndexOutOfBoundsException("Index Out of range (1115).");
 if(m_startData + i <= m_endData)
  return m_parent.m_binArray[m_startData + i];
 else
  return 0;
 }
}

Files类

/*
 * 创建日期 2006-7-29
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.kinstar.issuing.file;
/**
 * @author gongyifeng
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
import java.io.IOException;
import java.util.*;
// Referenced classes of package com.jspsmart.upload:
// File, SmartUpload
public class Files{
 private SmartUpload m_parent;
 private Hashtable m_files;
 private int m_counter;

 Files(){
 m_files = new Hashtable();
 m_counter = 0;
 }

 protected void addFile(File file){
 if(file == null)
 {
  throw new IllegalArgumentException("newFile cannot be null.");
 } else {
  m_files.put(new Integer(m_counter), file);
  m_counter++;
  return;
 }
 }

 public File getFile(int i)
 {
 if(i < 0)
 throw new IllegalArgumentException("File's index cannot be a negative value (1210).");
 File file = (File)m_files.get(new Integer(i));
 if(file == null)
 throw new IllegalArgumentException("Files' name is invalid or does not exist (1205).");
 else
 return file;
 }

 public int getCount()
 {
 return m_counter;
 }

 public long getSize() throws IOException
 {
 long l = 0L;
 for(int i = 0; i < m_counter; i++)
 l += getFile(i).getSize();

 return l;
 }

 public Collection getCollection()
 {
 return m_files.values();
 }

 public Enumeration getEnumeration()
 {
 return m_files.elements();
 }
}

Request类

/*
 * 创建日期 2006-7-29
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.kinstar.issuing.file;
/**
 * @author gongyifeng
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
import java.util.Enumeration;
import java.util.Hashtable;
public class Request
{
 private Hashtable m_parameters;
 private int m_counter;

 Request(){
 m_parameters = new Hashtable();
 m_counter = 0;
 }

 protected void putParameter(String s, String s1) {
 if(s == null)
  throw new IllegalArgumentException("The name of an element cannot be null.");
 if(m_parameters.containsKey(s))
 {
  Hashtable hashtable = (Hashtable)m_parameters.get(s);
  hashtable.put(new Integer(hashtable.size()), s1);
 } else{
  Hashtable hashtable1 = new Hashtable();
  hashtable1.put(new Integer(0), s1);
  m_parameters.put(s, hashtable1);
  m_counter++;
 }
 }

 public String getParameter(String s){
 if(s == null)
 throw new IllegalArgumentException("Form's name is invalid or does not exist (1305).");
 Hashtable hashtable = (Hashtable)m_parameters.get(s);
 if(hashtable == null)
 return null;
 else
 return (String)hashtable.get(new Integer(0));
 }

 public Enumeration getParameterNames()
 {
 return m_parameters.keys();
 }

 public String[] getParameterValues(String s)
 {
 if(s == null)
  throw new IllegalArgumentException("Form's name is invalid or does not exist (1305).");
 Hashtable hashtable = (Hashtable)m_parameters.get(s);
 if(hashtable == null)
  return null;
 String as[] = new String[hashtable.size()];
 for(int i = 0; i < hashtable.size(); i++)
  as[i] = (String)hashtable.get(new Integer(i));

 return as;
 }
}

SmartUpload类

/*
 * 创建日期 2006-7-29
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.kinstar.issuing.file;
/**
 * @author gongyifeng
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
// Referenced classes of package com.jspsmart.upload:
// Files, Request, SmartUploadException, File
public class SmartUpload
{
 protected byte m_binArray[];
 protected HttpServletRequest m_request;
 protected HttpServletResponse m_response;
 protected ServletContext m_application;
 private int m_totalBytes;
 private int m_currentIndex;
 private int m_startData;
 private int m_endData;
 private String m_boundary;
 private long m_totalMaxFileSize;
 private long m_maxFileSize;
 private Vector m_deniedFilesList;
 private Vector m_allowedFilesList;
 private boolean m_denyPhysicalPath;
 private boolean m_forcePhysicalPath;
 private String m_contentDisposition;
 public static final int SAVE_AUTO = 0;
 public static final int SAVE_VIRTUAL = 1;
 public static final int SAVE_PHYSICAL = 2;
 private Files m_files;
 private Request m_formRequest;

 public SmartUpload()
 {
 m_totalBytes = 0;
 m_currentIndex = 0;
 m_startData = 0;
 m_endData = 0;
 m_boundary = new String();
 m_totalMaxFileSize = 0L;
 m_maxFileSize = 0L;
 m_deniedFilesList = new Vector();
 m_allowedFilesList = new Vector();
 m_denyPhysicalPath = false;
 m_forcePhysicalPath = false;
 m_contentDisposition = new String();
 m_files = new Files();
 m_formRequest = new Request();
 }

 public final void init(ServletConfig servletconfig) throws ServletException
 {
 m_application = servletconfig.getServletContext();
 }

 public void service(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)throws ServletException, IOException
 {
 m_request = httpservletrequest;
 m_response = httpservletresponse;
 }

 public final void initialize(ServletConfig servletconfig, HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)throws ServletException
 {
 m_application = servletconfig.getServletContext();
 m_request = httpservletrequest;
 m_response = httpservletresponse;
 }

 public final void initialize(PageContext pagecontext)throws ServletException
 {
 m_application = pagecontext.getServletContext();
 m_request = (HttpServletRequest)pagecontext.getRequest();
 m_response = (HttpServletResponse)pagecontext.getResponse();
 }

 public final void initialize(ServletContext servletcontext, HttpSession httpsession, HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, JspWriter jspwriter) throws ServletException
 {
 m_application = servletcontext;
 m_request = httpservletrequest;
 m_response = httpservletresponse;
 }

 public void upload()throws ServletException, IOException, SmartUploadException
 {
 int i = 0;
 boolean flag = false;
 long l = 0L;
 boolean flag1 = false;
 String s = new String();
 String s2 = new String();
 String s4 = new String();
 String s5 = new String();
 String s6 = new String();
 String s7 = new String();
 String s8 = new String();
 String s9 = new String();
 String s10 = new String();
 boolean flag2 = false;
 m_totalBytes = m_request.getContentLength();
 m_binArray = new byte[m_totalBytes];
 int j;
 for(; i < m_totalBytes; i += j)
 try
 {
  m_request.getInputStream();
  j = m_request.getInputStream().read(m_binArray, i, m_totalBytes - i);
 }
 catch(Exception exception)
 {
  throw new SmartUploadException("Unable to upload.");
 }

 for(; !flag1 && m_currentIndex < m_totalBytes; m_currentIndex++)
 if(m_binArray[m_currentIndex] == 13)
  flag1 = true;
 else
  m_boundary = m_boundary + (char)m_binArray[m_currentIndex];

 if(m_currentIndex == 1)
  return;
 for(m_currentIndex++; m_currentIndex < m_totalBytes; m_currentIndex = m_currentIndex + 2)
 {
  String s1 = getDataHeader();
  m_currentIndex = m_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(m_deniedFilesList.contains(s5))
   throw new SecurityException("The extension of the file is denied to be uploaded (1015).");
  if(!m_allowedFilesList.isEmpty() && !m_allowedFilesList.contains(s5))
   throw new SecurityException("The extension of the file is not allowed to be uploaded (1010).");
  if(m_maxFileSize > 0L && (long)((m_endData - m_startData) + 1) > m_maxFileSize)
   throw new SecurityException("Size exceeded for this file : " + s4 + " (1105).");
  l += (m_endData - m_startData) + 1;
  if(m_totalMaxFileSize > 0L && l > m_totalMaxFileSize)
   throw new SecurityException("Total File Size exceeded (1110).");
  }
  if(flag3)
  {
  com.kinstar.issuing.file.File file = new com.kinstar.issuing.file.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)
   m_startData = m_startData + 128;
   file.setSize((m_endData - m_startData) + 1);
   file.setStartData(m_startData);
   file.setEndData(m_endData);
   m_files.addFile(file);
  } else
  {
   String s11 = new String(m_binArray, m_startData, (m_endData - m_startData) + 1);
   m_formRequest.putParameter(s3, s11);
  }
  if((char)m_binArray[m_currentIndex + 1] == '-')
   break;
  }

  }

 public int save(String s)throws ServletException, IOException, SmartUploadException
 {
 return save(s, 0);
 }

 public int save(String s, int i)throws ServletException, IOException, SmartUploadException
 {
 int j = 0;
 if(s == null)
  s = m_application.getRealPath("/");
 if(s.indexOf("/") != -1)
 {
  if(s.charAt(s.length() - 1) != '/')
  s = s + "/";
  } else
  if(s.charAt(s.length() - 1) != '\\')
  s = s + "\\";
  for(int k = 0; k < m_files.getCount(); k++)
  if(!m_files.getFile(k).isMissing())
  {
  m_files.getFile(k).saveAs(s + m_files.getFile(k).getFileName(), i);
  j++;
 }

 return j;
 }

 public int getSize()
 {
 return m_totalBytes;
 }

 public byte getBinaryData(int i)
 {
 byte byte0;
 try
 {
  byte0 = m_binArray[i];
 }
 catch(Exception exception)
 {
  throw new ArrayIndexOutOfBoundsException("Index out of range (1005).");
 }
 return byte0;
 }

 public Files getFiles()
 {
 return m_files;
 }

 public Request getRequest()
 {
 return m_formRequest;
 }

 public void downloadFile(String s) throws ServletException, IOException, SmartUploadException
 {
 downloadFile(s, null, null);
 }

 public void downloadFile(String s, String s1) throws ServletException, IOException, SmartUploadException, SmartUploadException
 {
 downloadFile(s, s1, null);
 }

 public void downloadFile(String s, String s1, String s2)throws ServletException, IOException, SmartUploadException
 {
 downloadFile(s, s1, s2, 65000);
 }

 public void downloadFile(String s, String s1, String s2, int i)throws ServletException, IOException, SmartUploadException
 {
 if(s == null)
  throw new IllegalArgumentException("File '" + s + "' not found (1040).");
 if(s.equals(""))
  throw new IllegalArgumentException("File '" + s + "' not found (1040).");
 if(!isVirtual(s) && m_denyPhysicalPath)
  throw new SecurityException("Physical path is denied (1035).");
 if(isVirtual(s))
  s = m_application.getRealPath(s);
 java.io.File file = new java.io.File(s);
 FileInputStream fileinputstream = new FileInputStream(file);
 long l = file.length();
 boolean flag = false;
 int k = 0;
 byte abyte0[] = new byte[i];
 if(s1 == null)
  m_response.setContentType("application/x-msdownload");
 else
 if(s1.length() == 0)
  m_response.setContentType("application/x-msdownload");
 else
  m_response.setContentType(s1);
 m_response.setContentLength((int)l);
 m_contentDisposition = m_contentDisposition != null ? m_contentDisposition : "attachment;";
 if(s2 == null)
  m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + getFileName(s));
 else
 if(s2.length() == 0)
  m_response.setHeader("Content-Disposition", m_contentDisposition);
 else
  m_response.setHeader("Content-Disposition", m_contentDisposition + " filename=" + s2);
 while((long)k < l)
 {
  int j = fileinputstream.read(abyte0, 0, i);
  k += j;
  m_response.getOutputStream().write(abyte0, 0, j);
 }
 fileinputstream.close();
 }

 public void downloadField(ResultSet resultset, String s, String s1, String s2) throws ServletException, IOException, SQLException
 {
 if(resultset == null)
 throw new IllegalArgumentException("The RecordSet cannot be null (1045).");
 if(s == null)
 throw new IllegalArgumentException("The columnName cannot be null (1050).");
 if(s.length() == 0)
 throw new IllegalArgumentException("The columnName cannot be empty (1055).");
 byte abyte0[] = resultset.getBytes(s);
 if(s1 == null)
 m_response.setContentType("application/x-msdownload");
 else
 if(s1.length() == 0)
 m_response.setContentType("application/x-msdownload");
 else
 m_response.setContentType(s1);
 m_response.setContentLength(abyte0.length);
 if(s2 == null)
 m_response.setHeader("Content-Disposition", "attachment;");
 else
 if(s2.length() == 0)
 m_response.setHeader("Content-Disposition", "attachment;");
 else
 m_response.setHeader("Content-Disposition", "attachment; filename=" + s2);
 m_response.getOutputStream().write(abyte0, 0, abyte0.length);
 }

 public void fieldToFile(ResultSet resultset, String s, String s1)throws ServletException, IOException, SmartUploadException, SQLException
 {
 try
 {
  if(m_application.getRealPath(s1) != null)
  s1 = m_application.getRealPath(s1);
  InputStream inputstream = resultset.getBinaryStream(s);
  FileOutputStream fileoutputstream = new FileOutputStream(s1);
  int i;
  while((i = inputstream.read()) != -1)
  fileoutputstream.write(i);
  fileoutputstream.close();
 }
 catch(Exception exception)
 {
  throw new SmartUploadException("Unable to save file from the DataBase (1020).");
 }
 }

 private String getDataFieldValue(String s, String s1)
 {
 String s2 = new String();
 String s3 = new String();
 int i = 0;
 boolean flag = false;
 boolean flag1 = false;
 boolean flag2 = false;
 s2 = s1 + "=" + '"';
 i = s.indexOf(s2);
 if(i > 0)
 {
  int j = i + s2.length();
  int k = j;
  s2 = "\"";
  int l = s.indexOf(s2, j);
  if(k > 0 && l > 0)
  s3 = s.substring(k, l);
 }
 return s3;
 }

 private String getFileExt(String s)
 {
 String s1 = new String();
 int i = 0;
 int j = 0;
 if(s == null)
  return null;
 i = s.lastIndexOf(46) + 1;
 j = s.length();
 s1 = s.substring(i, j);
 if(s.lastIndexOf(46) > 0)
  return s1;
 else
 return "";
 }

 private String getContentType(String s)
 {
 String s1 = new String();
 String s2 = new String();
 int i = 0;
 boolean flag = false;
 s1 = "Content-Type:";
 i = s.indexOf(s1) + s1.length();
 if(i != -1)
 {
  int j = s.length();
  s2 = s.substring(i, j);
 }
 return s2;
 }

 private String getTypeMIME(String s)
 {
 String s1 = new String();
 int i = 0;
 i = s.indexOf("/");
 if(i != -1)
  return s.substring(1, i);
 else
 return s;
 }

 private String getSubTypeMIME(String s)
 {
 String s1 = new String();
 int i = 0;
 boolean flag = false;
 i = s.indexOf("/") + 1;
 if(i != -1)
 {
  int j = s.length();
  return s.substring(i, j);
 } else
 {
  return s;
 }
 }

 private String getContentDisp(String s)
 {
 String s1 = new String();
 int i = 0;
 int j = 0;
 i = s.indexOf(":") + 1;
 j = s.indexOf(";");
 s1 = s.substring(i, j);
 return s1;
 }

 private void getDataSection()
 {
 boolean flag = false;
 String s = new String();
 int i = m_currentIndex;
 int j = 0;
 int k = m_boundary.length();
 m_startData = m_currentIndex;
 m_endData = 0;
 while(i < m_totalBytes)
 if(m_binArray[i] == (byte)m_boundary.charAt(j))
 {
  if(j == k - 1)
  {
  m_endData = ((i - k) + 1) - 3;
  break;
  }
  i++;
  j++;
 } else
 {
  i++;
  j = 0;
 }
 m_currentIndex = m_endData + k + 3;
 }

 private String getDataHeader()
 {
 int i = m_currentIndex;
 int j = 0;
 boolean flag = false;
 for(boolean flag1 = false; !flag1;)
 if(m_binArray[m_currentIndex] == 13 && m_binArray[m_currentIndex + 2] == 13)
 {
  flag1 = true;
  j = m_currentIndex - 1;
  m_currentIndex = m_currentIndex + 2;
 } else
 {
  m_currentIndex++;
 }

 String s = new String(m_binArray, i, (j - i) + 1);
 return s;
 }

 private String getFileName(String s)
 {
 String s1 = new String();
 String s2 = new String();
 int i = 0;
 boolean flag = false;
 boolean flag1 = false;
 boolean flag2 = false;
 i = s.lastIndexOf(47);
 if(i != -1)
  return s.substring(i + 1, s.length());
 i = s.lastIndexOf(92);
 if(i != -1)
  return s.substring(i + 1, s.length());
 else
 return s;
 }

 public void setDeniedFilesList(String s) throws ServletException, IOException, SQLException
 {
 String s1 = "";
 if(s != null)
 {
 String s2 = "";
 for(int i = 0; i < s.length(); i++)
 if(s.charAt(i) == ',')
 {
  if(!m_deniedFilesList.contains(s2))
  m_deniedFilesList.addElement(s2);
  s2 = "";
 } else
 {
  s2 = s2 + s.charAt(i);
 }

 if(s2 != "")
  m_deniedFilesList.addElement(s2);
 } else
 {
  m_deniedFilesList = null;
 }
 }

 public void setAllowedFilesList(String s)
 {
 String s1 = "";
 if(s != null)
 {
  String s2 = "";
  for(int i = 0; i < s.length(); i++)
  if(s.charAt(i) == ',')
  {
  if(!m_allowedFilesList.contains(s2))
  m_allowedFilesList.addElement(s2);
  s2 = "";
  } else
  {
  s2 = s2 + s.charAt(i);
  }

  if(s2 != "")
  m_allowedFilesList.addElement(s2);
 } else
 {
  m_allowedFilesList = null;
 }
 }

 public void setDenyPhysicalPath(boolean flag)
 {
 m_denyPhysicalPath = flag;
 }

 public void setForcePhysicalPath(boolean flag)
 {
 m_forcePhysicalPath = flag;
 }

 public void setContentDisposition(String s)
 {
 m_contentDisposition = s;
 }

 public void setTotalMaxFileSize(long l)
 {
 m_totalMaxFileSize = l;
 }

 public void setMaxFileSize(long l)
 {
 m_maxFileSize = l;
 }

 protected String getPhysicalPath(String s, int i)throws IOException
 {
 String s1 = new String();
 String s2 = new String();
 String s3 = new String();
 boolean flag = false;
 s3 = System.getProperty("file.separator");
 if(s == null)
  throw new IllegalArgumentException("There is no specified destination file (1140).");
 if(s.equals(""))
  throw new IllegalArgumentException("There is no specified destination file (1140).");
 if(s.lastIndexOf("\\") >= 0)
 {
  s1 = s.substring(0, s.lastIndexOf("\\"));
  s2 = s.substring(s.lastIndexOf("\\") + 1);
 }
 if(s.lastIndexOf("/") >= 0)
 {
  s1 = s.substring(0, s.lastIndexOf("/"));
  s2 = s.substring(s.lastIndexOf("/") + 1);
 }
 s1 = s1.length() != 0 ? s1 : "/";
 java.io.File file = new java.io.File(s1);
 if(file.exists())
  flag = true;
 if(i == 0)
 {
  if(isVirtual(s1))
  {
  s1 = m_application.getRealPath(s1);
  if(s1.endsWith(s3))
   s1 = s1 + s2;
  else
  s1 = s1 + s3 + s2;
   return s1;
  }
  if(flag)
  {
  if(m_denyPhysicalPath)
   throw new IllegalArgumentException("Physical path is denied (1125).");
  else
   return s;
  } else
  {
  throw new IllegalArgumentException("This path does not exist (1135).");
  }
 }
 if(i == 1)
 {
  if(isVirtual(s1))
  {
  s1 = m_application.getRealPath(s1);
  if(s1.endsWith(s3))
  s1 = s1 + s2;
  else
  s1 = s1 + s3 + s2;
  return s1;
 }
 if(flag)
  throw new IllegalArgumentException("The path is not a virtual path.");
 else
  throw new IllegalArgumentException("This path does not exist (1135).");
 }
 if(i == 2)
 {
  if(flag)
  if(m_denyPhysicalPath)
  throw new IllegalArgumentException("Physical path is denied (1125).");
  else
  return s;
  if(isVirtual(s1))
  throw new IllegalArgumentException("The path is not a physical path.");
  else
  throw new IllegalArgumentException("This path does not exist (1135).");
 } else
 {
  return null;
 }
 }

 public void uploadInFile(String s)throws IOException, SmartUploadException
 {
 int i = 0;
 int j = 0;
 boolean flag = false;
 if(s == null)
  throw new IllegalArgumentException("There is no specified destination file (1025).");
 if(s.length() == 0)
  throw new IllegalArgumentException("There is no specified destination file (1025).");
 if(!isVirtual(s) && m_denyPhysicalPath)
  throw new SecurityException("Physical path is denied (1035).");
 i = m_request.getContentLength();
 m_binArray = new byte[i];
 int k;
 for(; j < i; j += k)
 try
 {
  k = m_request.getInputStream().read(m_binArray, j, i - j);
 }
 catch(Exception exception)
 {
  throw new SmartUploadException("Unable to upload.");
 }

 if(isVirtual(s))
  s = m_application.getRealPath(s);
 try
 {
  java.io.File file = new java.io.File(s);
  FileOutputStream fileoutputstream = new FileOutputStream(file);
  fileoutputstream.write(m_binArray);
  fileoutputstream.close();
 }
 catch(Exception exception1)
 {
  throw new SmartUploadException("The Form cannot be saved in the specified file (1030).");
 }
 }

 private boolean isVirtual(String s)
 {
 if(m_application.getRealPath(s) != null)
 {
  java.io.File file = new java.io.File(m_application.getRealPath(s));
  return file.exists();
 } else
 {
  return false;
 }
 }
}

SmartUploadException 类

/*
 * 创建日期 2006-7-29
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.kinstar.issuing.file;
/**
 * @author gongyifeng
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class SmartUploadException extends Exception
{
 SmartUploadException(String s)
 {
 super(s);
 }
}

上传的Servlet

package com.kinstar.issuing.action;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kinstar.issuing.file.File;
import com.kinstar.issuing.file.SmartUpload;
import com.kinstar.issuing.objects.t_user;
import com.kinstar.issuing.operation.UserOperation;
import com.kinstar.issuing.program.programService;
import com.kinstar.issuing.session.SessionGloble;
import com.kinstar.issuing.util.StringUtil;
/**
 * @version 1.0
 * @author gyf
 */

public class upload2ProgramAction extends HttpServlet{
 private ServletConfig config;
 /**
 * 初始化Servlet
 */
 final public void init(ServletConfig config) throws ServletException {
 this.config = config;
 }
 /**
 * 处理GET请求
 */
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request,response);
 }

 /**
 * 响应POST请求
 */
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  int count=0;
  SmartUpload mySmartUpload = new SmartUpload();
  try {
   // 初始化
   mySmartUpload.initialize(config,request,response);

   // 上载
   mySmartUpload.upload();
   com.kinstar.issuing.file.File f1 = mySmartUpload.getFiles().getFile(0);
  // com.kinstar.issuing.file.File f2 = mySmartUpload.getFiles().getFile(1);
   String backPic = f1.getFileName();
  //String name2 = f2.getFileName();

   long size=0;

  // 保存上载文件到指定目录
  count=mySmartUpload.save("ads");
  response.sendRedirect("program.jsp?dopass=ture");

  }   

  catch (Exception e){
   response.sendRedirect("fail.jsp");
  }
}

2.common-fileupload组件

挺好用的,也能够上传大文件,我试过,300M以上的文件上传本地传非常快,异地测试也能够上传成功.

首先要下载org.apache.commons.fileupload包和org.apache.commons.io包

下面是我的servlet

package com.kinstar.issuing.action;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.regex.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import com.kinstar.issuing.objects.t_user;
import com.kinstar.issuing.operation.UserOperation;
import com.kinstar.issuing.program.programService;
import com.kinstar.issuing.session.SessionGloble;
import com.kinstar.issuing.util.StringUtil;
/**
 * @version 1.0
 * @author gyf
 */

public class uploadProgramAction extends HttpServlet{
 private static final String CONTENT_TYPE = "text/html; charset=GB2312";

 /**
 * 处理GET请求
 */
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request,response);
 }

 /**
 * 响应POST请求
 */
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // 变量定义
  response.setContentType(CONTENT_TYPE);
  HttpSession modifysession=request.getSession();
  SessionGloble logonUser;
  logonUser=(SessionGloble)modifysession.getAttribute("UserInfo");
    if(logonUser==null){
    response.sendRedirect("mainindex.jsp");
  }
  t_user userinfo=new t_user();
  UserOperation user=null;
  try {
   user = new UserOperation();
  } catch (Exception e1) {
  // TODO 自动生成 catch 块
  e1.printStackTrace();
  }
  try {
   userinfo=user.getUser(logonUser.getUserId());
  } catch (Exception e2) {
  // TODO 自动生成 catch 块
  e2.printStackTrace();
  }
   //System.out.println("figure="+userinfo.getUserFigure());
   PrintWriter out=response.getWriter();
   DateFormat updf = new SimpleDateFormat("yyyyMMddHHmm");
   String updateTime = updf.format(new Date());
   int isNeed = 0;
   String IsCheck="0";

  //省农行用户上传的节目必需显示,且审批已经合格
   if(userinfo.getUserFigure().equals("1")){
   isNeed = 1;
   IsCheck = "1";
   }
   else{
   isNeed = 0;
   IsCheck = "0";
   }
  int type=0;
  String avaTime="";
  String screen="";
  int fileTime=0;
  int fileTimeReal=0;
  int circle=0;
  String picSwitch="";
  String deleState="1";
  String backPic="";

  String fieldName="";
  String finalName="";
  String fileNameReal="";
  long size=0;
  String name="";
   try {
  DiskFileUpload fu = new DiskFileUpload();
  // 设置允许用户上传文件大小,单位:字节,这里设为2m
  fu.setSizeMax(5*1024*1024*1024);
  // 设置最多只允许在内存中存储的数据,单位:字节
  fu.setSizeThreshold(10*1024*1024);
  // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
  fu.setRepositoryPath("C:\\WINDOWS\\Temp\\");
  //开始读取上传信息
  List fileItems = fu.parseRequest(request);
  //依次处理每个上传的文件
  Iterator iter = fileItems.iterator();

    //正则匹配,过滤路径取文件名
  String regExp=".+\\\\(.+)$";

  //过滤掉的文件类型
  String[] errorType={".exe",".com",".cgi",".asp"};

  Pattern p = Pattern.compile(regExp);
  StringUtil su = new StringUtil();

  while (iter.hasNext()) {
   FileItem item = (FileItem)iter.next();

    if(item.isFormField()) {
    // 获得表单域的名字
    fieldName = item.getFieldName();
    // 如果表单域的名字是name…
    if(fieldName.equals("type"))
      type = Integer.parseInt(item.getString());

    }
   if (!item.isFormField()) {
    name = item.getName();
    size = item.getSize();
    if((name==null||name.equals("")) && size==0)
    continue;
    Matcher m = p.matcher(name);
    boolean result = m.find();
    if (result){
    for (int temp=0;temp<errorType.length;temp++){
    if (m.group(1).endsWith(errorType[temp])){
    throw new IOException(name+": wrong type");
    }
    }

    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = df.format(new Date());
    fileNameReal=date+m.group(1);
    finalName=date+Math.round(Math.random()*10000)+fileNameReal.substring(fileNameReal.indexOf("."));
    //保存上传的文件到指定的目录
    //在下文中上传文件至数据库时,将对这里改写
    item.write(new File(getServletContext().getRealPath(".//ads//")+finalName));
    //out.print(finalName+size);
    }
    else
    {
   throw new IOException("fail to upload");

    }
   }
   if(item.isFormField()) {
   // 获得表单域的名字
   fieldName = item.getFieldName();
   if(fieldName.equals("avaTime"))
   avaTime=item.getString();
   if(fieldName.equals("screen"))
   screen=item.getString();
   if(fieldName.equals("fileTime"))
   fileTime = Integer.parseInt(item.getString());
   if(fieldName.equals("fileTimeReal"))
   fileTimeReal = Integer.parseInt(item.getString());
   if(fieldName.equals("circle"))
   circle = Integer.parseInt(item.getString());
   if(fieldName.equals("switchPic"))
    picSwitch = item.getString(); 

   }
    }
   }catch (IOException e){
    out.println(e);
   }catch (FileUploadException e){
    out.println(e);
   } catch (Exception e) {
  // TODO 自动生成 catch 块
   e.printStackTrace();
   }
   if(finalName.equals("")){
    response.sendRedirect("fail.jsp");
   }
   else{
  try {
  programService ps = new programService();
  ps.insertProgram(userinfo.getUserId(),updateTime,type,finalName,size,isNeed,avaTime,deleState,IsCheck,userinfo.getCity(),backPic,screen,fileTime,fileTimeReal,picSwitch,circle,userinfo.getUserFigure(),new String(fileNameReal.getBytes("GB2312"),"ISO8859-1"));
  response.sendRedirect("program.jsp?dopass=true");
  } catch (Exception e3) {
  // TODO 自动生成 catch 块
  e3.printStackTrace();
  }
   }
  }
}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(0)

相关推荐

  • FasfDFS整合Java实现文件上传下载功能实例详解

    在上篇文章给大家介绍了FastDFS安装和配置整合Nginx-1.13.3的方法,大家可以点击查看下. 今天使用Java代码实现文件的上传和下载.对此作者提供了Java API支持,下载fastdfs-client-java将源码添加到项目中.或者在Maven项目pom.xml文件中添加依赖 <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</arti

  • Java与WebUploader相结合实现文件上传功能(实例代码)

    之前自己写小项目的时候也碰到过文件上传的问题,没有找到很好的解决方案.虽然之前网找各种解决方案的时候也看到过WebUploader,但没有进一步深究.这次稍微深入了解了些,这里也做个小结. 简单的文件和普通数据上传并保存 jsp页面: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE h

  • java 文件上传(单文件与多文件)

    java 文件上传(单文件与多文件) 一.简述 一个javaWeb项目中,文件上传功能几乎是必不可少的,本人在项目开发中也时常会遇到,以前也没怎么去理它,今天有空学习了一下这方面的知识,于是便将本人学到的SpringMVC中单文件与多文件上传这部分知识做下笔记. 二.单文件上传 1.页面 这里以一个简单的表单提交为例子,文件上传需要将表单的提交方法设置为post,将enctype的值设置为"multipart/form-data". <form action="${pa

  • Java Servlet简单实例分享(文件上传下载demo)

    项目结构 src com servletdemo DownloadServlet.java ShowServlet.java UploadServlet.java WebContent jsp servlet download.html fileupload.jsp input.jsp WEB-INF lib commons-fileupload-1.3.1.jar commons-io-2.4.jar 1.简单实例 ShowServlet.java package com.servletdem

  • Java Web使用Html5 FormData实现多文件上传功能

    前一阵子,迭代一个线上的项目,其中有一个图片上传的功能,之前用的ajaxfileupload.js来实现上传的,不过由于ajaxfileupload.js,默认是单文件上传(虽然可以通过修改源码的方法来实现多文件上传),又加上是在移动端做的,所以就打算采用html5的FormData实现多文件上传 首先html页面定义有两种: Html1 <form enctype="multipart/form-data" id="formfile"> <inp

  • JAVA SFTP文件上传、下载及批量下载实例

    1.jsch官方API查看地址(附件为需要的jar) http://www.jcraft.com/jsch/ 2.jsch简介 JSch(Java Secure Channel)是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序. SFTP(Secure File Transfer Protocol)安全文件传送协议.可以为传输文件提供一种安全的加密方法.SFTP 为 SSH的一部份,是一种传输

  • Java 文件上传的实例详解

    Java 文件上传的实例详解 java 文件上传 Java文件上传,介绍几种常用的方法,也是经过本人亲手调试过的 1.jspsmartupload 这个组件用起来是挺方便的,不过就是只适合小文件上传,如果大文件上传的话就不行,查看了一下他的代码,m_totalBytes = m_request.getContentLength(); m_binArray = new byte[m_totalBytes];居然把整个上传文件都读到内存去了,那如果是上传几十M的文件,同时几个用户上传,服务器稳挂,不

  • 最详细的文件上传下载实例详解(推荐)

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件.这个common-fileupload上传组件的jar包可以去apache官网上面下载,也可以在struts的lib文件夹下面找到,stru

  • PHP文件上传类实例详解

    本文实例讲述了PHP文件上传类.分享给大家供大家参考,具体如下: 这里演示了FileUpload.class.php文件上传类,其中用到了两个常量,可在网站配置文件中定义: define('ROOT_PATH',dirname(__FILE__)); //网站根目录 define('UPDIR','/uploads/'); //上传主目录 具体代码如下: <?php //上传文件类 class FileUpload { private $error; //错误代码 private $maxsiz

  • PHP文件上传操作实例详解

    本文实例分析了PHP文件上传操作.分享给大家供大家参考,具体如下: 文件上传 发生在浏览器向服务器发出的请求中. 文件,对于浏览器来讲,就是表单中的一个特殊类型的数据而已. 浏览器表单中的数据,两种类型: 字符串类型(字节流编码) 文件类型(二进制编码),文件是表单数据中一部分 服务器角度: 在接受浏览器请求时,处理好表单内的数据.根据数据类型不同使用不同处理方法: 字符串类型,存储在$_POST变量中(内存) 文件型数据,存储在上传临时目录中 表单提交时,浏览器会默认的行为: 表单内的的内容都

  • TP3.2.3框架文件上传操作实例详解

    本文实例讲述了TP3.2.3框架文件上传操作.分享给大家供大家参考,具体如下: 上传表单 在ThinkPHP中使用上传功能无需进行特别处理.例如,下面是一个带有附件上传的表单提交: <form action="__URL__/upload" enctype="multipart/form-data" method="post" > <input type="text" name="name"

  • Java 中HttpURLConnection附件上传的实例详解

    Java 中HttpURLConnection附件上传的实例详解 整合了一个自己写的采用Http做附件上传的工具,分享一下! 示例代码: /** * 以Http协议传输文件 * * @author mingxue.zhang@163.com * */ public class HttpPostUtil { private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJK

  • jQuery File Upload文件上传插件使用详解

    jQuery File Upload 是一个Jquery文件上传组件,支持多文件上传.取消.删除,上传前缩略图预览.列表显示图片大小,支持上传进度条显示:支持各种动态语言开发的服务器端. 官网链接:https://github.com/blueimp/jQuery-File-Upload/wiki 特点:拖放支持:上传进度条:图像预览:可定制和可扩展的:兼容任何服务器端应用平台(PHP, Python, Ruby on Rails, Java, Node.js, Go etc.). 使用方法:

  • SpringBoot整合MinIO实现文件上传的方法详解

    目录 前言 1. MinIO 简介 2. MinIO 安装 3. 整合 Spring Boot 4. 配置nginx 5. 小结 前言 现在 OSS 服务算是一个基础服务了,很多云服务厂商都有提供这样的服务,价格也不贵,松哥自己的网站用的就是类似的服务. 不过对于中小公司来说,除了购买 OSS 服务之外,也可以自己搭建专业的文件服务器,自己搭建专门的文件服务器的话,曾经比较专业的做法是 FastDFS,松哥之前也专门为之录过视频发在 B 站上,感兴趣的小伙伴可以自行查看.不过 FastDFS 搭

  • Spring实现文件上传的配置详解

    添加依赖 主要用来解析request请求流,获取文件字段名.上传文件名.content-type.headers等内容组装成FileItem <!--添加fileupload依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</versio

  • Bootstrap Fileinput文件上传组件用法详解

    最近时间空余,总结了一些关于bootstrap fileinput组件的一些常见用法,特此分享到我们平台,供大家参考,同时也方便以后的查找.本文写的不好还请见谅. 一.效果展示 1.原始的input type='file',简直不忍直视. 2.不做任何装饰的bootstrap fileinput:(bootstrap fileinput初级进化) 3.bootstrap fileinput高级进化:中文化.可拖拽上传.文件扩展名校验(如果不是需要的文件,不让上传) 拖拽上传 上传中 4.boot

随机推荐