文件上传(servlet 中含下载和删除操作)

个人认为,文件上传是一个较为独立的功能,有一定的统一性和规范性。因此,将它记录下来。
一般来说,文件上传的方法很多,可以应用商业javabean(如jspsmartupload),也可以用开源javabean(如Apache Commons FileUpload),或者独立更生,写一个自己的bean,这里我选择用开源bean,原因有二:1、免费,可扩展;2、功能一般较为完善和规范,省时省力。
以下是实现文件上传的一个实例,该实例的环境如下:
1、MSSQL 数据库
2、Ibatis做存储模式
一、数据库
CREATE   TABLE   [ dbo ] . [ attachment ] (
    
[ Sequence ]  NUMERIC( 10 , 0 IDENTITY ( 1 , 1 NOT   NULL ,
    
[ ObjectID ]  NUMERIC( 10 , 0 NULL ,
    
[ ObjectName ]   VARCHAR ( 256 NULL ,
    
[ FileName ]   VARCHAR ( 512 NULL ,
    
[ FileSize ]   INT   NULL ,
    
[ FileData ]   IMAGE   NULL ,
    
CONSTRAINT   [ PK_attachment ]   PRIMARY   KEY   CLUSTERED  ( [ Sequence ] )
)

二、POJO 类
public   class  Attachment  {
    
private int sequence;
    
private int objectId;
    
private String objectName;
    
private String fileName;
    
private int fileSize;
    
private byte[] fileData;
    
    
public byte[] getFileData() {
        
return fileData;
    }

    
public void setFileData(byte[] fileData) {
        
this.fileData = fileData;
    }

    
public String getFileName() {
        
return fileName;
    }

    
public void setFileName(String fileName) {
        
this.fileName = fileName;
    }


    
public int getObjectId() {
        
return objectId;
    }

    
public void setObjectId(int objectId) {
        
this.objectId = objectId;
    }

    
public String getObjectName() {
        
return objectName;
    }

    
public void setObjectName(String objectName) {
        
this.objectName = objectName;
    }

    
public int getSequence() {
        
return sequence;
    }

    
public void setSequence(int sequence) {
        
this.sequence = sequence;
    }

    
public int getFileSize() {
        
return fileSize;
    }

    
public void setFileSize(int fileSize) {
        
this.fileSize = fileSize;
    }

    

}

开始字段fileData 用了java.sql.Blob类型,后发现将InputStream转成Blob类型时较为棘手,所以专用了byte[]类型,不过也有办法,我想可以自己写个Blob类以实现,java.sql.Blob 这个接口。
三、SQLMap XML
   < resultMap  id ="attachmentResult"  class ="attachment" >
    
< result  property ="sequence"  column ="SEQUENCE"  nullValue ="0" />
    
< result  property ="objectId"  column ="OBJECTID"  nullValue ="0" />
    
< result  property ="objectName"  column ="OBJECTNAME"  nullValue ="" />
    
< result  property ="fileName"  column ="FILENAME"  nullValue ="" />
    
< result  property ="fileSize"  column ="FILESIZE"  nullValue ="0" />
    
< result  property ="fileData"  column ="FILEDATA"   />
  
</ resultMap >

  
< insert  id ="insertAttachment"  parameterClass ="attachment" >
    INSERT INTO ATTACHMENT (
        OBJECTID,
        OBJECTNAME,
        FILENAME,
        FILESIZE,
        FILEDATA
    )VALUES(
        #objectId#,
        #objectName:VARCHAR#,
        #fileName:VARCHAR#,
        #fileSize#,
        #fileData#
    )
    
< selectKey  resultClass ="int"  keyProperty ="sequence" >
        
<!--  SELECT SCOPE_IDENTITY() AS SEQUENCE  -->
        SELECT @@IDENTITY AS SEQUENCE
    
</ selectKey >
  
</ insert >
这里需要注意的是采用selectKey自动生成id时没有一个十全十美的办法,Ibatis官方网站有所讨论,具体参见
http://www.mail-archive.com/user-cs@ibatis.apache.org/msg01993.html
四、Implement  类
public   class  AttachmentDaoImpl  {

    
public static Integer insert(Attachment attachment) throws SQLException {
        
try {
            
return (Integer) IbatisHelper.getSqlMapper().insert(
                    
"insertAttachment", attachment);
        }
 catch (SQLException e) {
            e.printStackTrace();
            
return null;
        }

    }


}

五、Servlet
/**
 * Servlet implementation class for Servlet: UploadFile
 *
 
*/

 
public   class  UploadFile  extends  javax.servlet.http.HttpServlet  implements  javax.servlet.Servlet  {
    
    
/**
     * 
     
*/

    
private static final long serialVersionUID = 1L;
    
private static final String CONTENT_TYPE = "text/html;charset=gb2312";    
    
private static final String TEMP_PATH = "c:/windows/temp";
    
private static final String DESTINATION_PATH = "/attachment/";
    
private static final int MAX_MEMORY_SIZE = 2*1024*1024;
    
private static final int MAX_REQUEST_SIZE = 3*1024*1024;
    
private String fileName = "";
    
    
public String processUploadedFile(FileItem item){
        
boolean writeToFile = false;
        
// Process a file upload
        if (writeToFile) {
            File uploadedFile 
= new File(DESTINATION_PATH);
            
try {
                item.write(uploadedFile);
                
return "";
            }
 catch (Exception e) {
                e.printStackTrace();
                
return "Error:Write to file system failed.";
            }

            
        }
 else {
            
try {
                InputStream uploadedStream 
= item.getInputStream();
                
byte[] b = new byte[uploadedStream.available()];
                
int fileSize = b.length;
                uploadedStream.read(b);
                uploadedStream.close();
                Attachment attachment 
= new Attachment();
                attachment.setFileName(fileName);
                attachment.setFileSize(fileSize);
                attachment.setFileData(b);
                
try{
                    Integer key 
=  AttachmentDaoImpl.insert(attachment);
                    
return key.toString();
                }
catch(SQLException e){
                    e.printStackTrace();
                    
return "Error:Write to database failed.";
                }

            }
 catch (IOException e) {
                e.printStackTrace();
                
return "Error:I/O write failed.";
            }

        }

    }

    
    
public String processFormField(FileItem item){
        String fieldName 
= item.getFieldName();
        
if("FileName".equals(fieldName))
            fileName 
= item.getString();
        
return "";    
    }

    
    
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        
        String action 
= request.getParameter("action");
        String strId 
= request.getParameter("id");
        
if(null==strId||"".equals(strId)) {
            PrintWriter out 
= response.getWriter();
            out.println(
"Error:Attachment ID not found.");;
            
return;
        }

        
        
if("delete".equals(action.toLowerCase())){
            String sequence[] 
= {strId};
            String process 
= "";
            
try{
                process 
= AttachmentDaoImpl.delete(sequence);
                response.sendRedirect(
"../common/attachment.jsp");
            }
catch(SQLException e){
                e.printStackTrace();
            }

        }


        
if("download".equals(action.toLowerCase())){
            
//Get the attachment
            Attachment attach = null;
            
try{
                attach 
= AttachmentDaoImpl.getAttachment(strId);
            }
catch(SQLException e){
                e.printStackTrace();
            }

            
if(null!=attach){
                
//Set content type
                response.setContentType("application/x-tar");
                
//Set header
                response.setHeader("Content-disposition""attachment;filename="
                          
+ attach.getFileName());
                
//Output to client
                OutputStream os = response.getOutputStream();
                
byte[] buffer = attach.getFileData();
                os.write(buffer, 
0, buffer.length);
                os.close();
            }

        }

    }

    
    
/* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     
*/

    
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
// TODO Auto-generated method stub
        response.setContentType(CONTENT_TYPE);
        PrintWriter out 
= response.getWriter();
        
try{
            
//    Check that we have a file upload request
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            
if(!isMultipart){
                out.println(
"Not a file upload request.");
                
return;
            }

            
//    Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();;
            
//    Set factory constraints
            factory.setSizeThreshold(MAX_MEMORY_SIZE);
            File file 
= new File(TEMP_PATH);
            factory.setRepository(file);
            
//    Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            
//    Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            
//    Parse the request
            if(request.getContentLength()>MAX_REQUEST_SIZE){
                out.println(
"Error:Over max size to upload.");
                
return;
            }

            List items 
= upload.parseRequest(request);
            Iterator iter 
= items.iterator();
            
// Routine below doesn't adapt to return multiple ids.
            String strId = "";
            
while(iter.hasNext()){
                String process 
= "";
                FileItem item 
= (FileItem) iter.next();
                
if (item.isFormField()) {
                    process 
= processFormField(item);
                }
 else {
                    process 
= processUploadedFile(item);
                }

                System.out.println(process);
                
if(process.length()>0&&process.indexOf("Error")>-1){
                    out.println(process);
                    
return;
                }
else if(process.length()>0&&process.indexOf("Error")<0){
                    strId 
= process;
                }

            }

            
//    Return to attachment page
            response.sendRedirect("../common/attachment.jsp?id="+strId);
        }
catch(FileUploadException e){
            e.printStackTrace();
        }

    }
                 
}

六、文件上传Jsp页面
< form  name ="attachment"  enctype ="multipart/form-data"
    action
="../servlets/UploadFile"  method ="post"
    onsubmit
="return validateAttach()" >
< table  class ="nopadding"  border ="0"  cellpadding ="3"  cellspacing ="0" >
    
< tbody >
        
< tr >
            
< td  nowrap ="nowrap" > Choose a File : </ td >
            
< td  width ="0" >< input  name ="FileName"  type ="hidden"  value ="" >
            
< input  name ="AttachID"  value =""  type ="hidden"  value ="" >< input
                
name ="FilePath"  class ="formStyle"  size ="50"  style ="width: auto;"
                type
="file" ></ td >
        
</ tr >
        
< tr >
            
< td  align ="left"  nowrap ="nowrap"  valign ="top" > &nbsp; </ td >
            
< td  align ="left"  nowrap ="nowrap"  valign ="top" >< input
                
name ="ATTACH"  class ="formStylebutton"  value ="Attach"
                title
="Attach file"  type ="submit" ></ td >
        
</ tr >
    
</ tbody >
</ table >
</ form >
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值