java上传文件与文件夹到服务器

文件:

String basePath = ServletActionContext.getServletContext().getRealPath("share"); //服务器路径获取
        File savefile = new File(new File(basePath), uploadFileName);
        try {
            FileUtils.copyFile(upload, savefile);
        } catch (IOException e) {
            e.printStackTrace();
        }

文件夹:

public String mutiUpload(){

        if (folder == null) {
            path=path+"";
            return "mutiUpload";
        }
        File mutiFile=new File(folder);//folder为上传的文件夹全路径
        String parent=mutiFile.getParent();//你上传的文件夹的根路径
        try {
            uploadMuti(folder,parent);
        } catch (IOException e) {
            e.printStackTrace();
        }
        setSuccessNextUrl("window.location.href='contract/contractFtp!changeDir.action?path="
                    + path + "'");
        return SUCCESS;
    }

    public boolean uploadMuti(String folder,String originPath) throws IOException{
        File mutiFile=new File(folder);
            String basePath = ServletActionContext.getServletContext().getRealPath("share"); 
            String folderName=(mutiFile.getPath().replace(originPath, "")).replace("\\", "/");//文件夹名称
            String folderPath=basePath+"/"+folderName;
            File file=new File(folderPath);
            file.mkdir();
            File fileList[] = mutiFile.listFiles(); 
            for(File upfile : fileList){
                if (upfile.isDirectory()) {// 文件夹中还有文件夹 
                    folder=upfile.getPath();
                    uploadMuti(folder,originPath);
                }else{
                    String path=(upfile.getPath().replace(originPath, "")).replace("\\", "/");
                    String str[]=path.split("/");
                    String workpath="";
                    for(int i=0;i<str.length-1;i++){
                        workpath=workpath+"/"+str[i];
                    }
                    String filePath=basePath+workpath;
                    File savefile = new File(new File(filePath), upfile.getName());
                    try {
                        FileUtils.copyFile(upfile, savefile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        return true;
    }

自己使用过后发现这种做法只能在自己搭建服务器的情况下从本机上传到服务器,而无法从其他机器上传。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值