java上传_java上传文件

该博客内容涉及Java Web中jsp页面form的enctype属性设置,用于上传文件。通过JavaScript获取文件名和后缀,并在后台进行文件保存到服务器及附件表的存储操作。主要涉及文件流处理和文件路径构建。

jsp页面

form中的enctype属性应设置为:multipart/form-data

function fz(){

var aa=document.getElementById("file").value;

var arrS2=aa.split("\\");

var i=arrS2.length;

var filename= arrS2[i-1]

var arrb= aa.split("\.");

var j=arrb.length;

document.getElementById("file").value=aa;

document.getElementById("filename").value=filename;

document.getElementById("filepath").value="/uploadfiles/casus/"+filename;

document.getElementById("suffix").value=arrb[j-1];

}

action:

//附件相关

privateAttachmentMatters attachment;private String fileName; //名字

private String suffix; //后缀

privateString file;private String attachmentid;

/*** 上传*/

public voiduploadFile(){try{

String name=attachment.getFilename();

upload(this.file,name) ; //上传到服务器

//保存到附件表里

if(name!=null&&!name.equals("")){

attachment.setFilepath("uploadfiles/sss/"+name);

attachment.setUploadDate(new Date());

bean.saveObject(attachment);

}

}catch(Exception e){

e.printStackTrace();

}

}

public static voidupload(String file, String name){if(file !=null){

FileOutputStream outputStream;try{

String path=ServletActionContext.getRequest().getRealPath("/uploadfiles/matters");

String path1=path;

path1.replaceAll("\\u002E\\u002E", "2");

String fileDir= path+File.separator;

String filePath=fileDir+name;

File f=newFile(fileDir);

f.mkdirs();

outputStream= newFileOutputStream(filePath);

FileInputStream fileIn= newFileInputStream(file);byte[] buffer = new byte[128];intlen;while ((len = fileIn.read(buffer))>0){

outputStream.write(buffer,0, len);

}

fileIn.close();

outputStream.close();

}catch(Exception e) {

e.printStackTrace();

}

}else{

System.out.println("文件为空");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值