文件上传类

 package com.xiao.company.filter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

/*
 * 此类是专为文件上传用
 */




public class Upload extends DispatchAction
{
    public String upload(FormFile file,String servletContext)
    {  
//            String servletContext=servlet.getServletContext().getRealPath("/");  //获取项目在系统(服务器)中的路径(包含项目名在内),即项目的根目录        
//            System.out.println("当然2项目路径为:  "+servletContext);
            Date da=new Date();
            long m=da.getTime();
           
            String fileName=file.getFileName();
            
            String fileType=fileName.substring(fileName.lastIndexOf("."));
            fileName=m+fileType;            
            int filesize = (int) (file.getFileSize());            
            InputStream streamIn=null;
            OutputStream streamOut=null;
    
            String ownerfile="/images/photo";    
            String vlocation=ownerfile+"/"+fileName;    
            String plocation=servletContext+vlocation;            
            File rootDir=new File(servletContext+ownerfile);            
            try {
                
                int by=0;
                byte [] bu=new byte[filesize];
                if(!rootDir.isDirectory())
                    rootDir.mkdirs();
                streamIn=file.getInputStream();
                streamOut=new FileOutputStream(plocation);
                while((by=streamIn.read(bu,0,filesize))!=-1)
                {
                    streamOut.write(bu,0,by);
                }
                streamOut.close();
                streamIn.close();
                return fileName;
            } catch (FileNotFoundException e)
            {
                // TODO 自动生成 catch 块
                e.printStackTrace();
            } catch (IOException e)
            {
                // TODO 自动生成 catch 块
                e.printStackTrace();
        }
            
      
       return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值