servlet上传文件是,servlet封装了一个ServletInputStream,以下是我写的上传文件,对于我的电脑来说是服务器,上传就是讲一个文件放到我电脑的一个地方,以下代码,我实现了
1.对于任意文件格式的上传,包括txt,docx,png,MP3等上传,
2.不同时间多人上传文件,并且名字相同,对于这个问题,我创建了以时间为名字的文件夹目录,
3。同一时间多人同时访问服务器,上传文件,并且名字相同,对于这个问题,由于我只是菜鸟,刚起步,就用了随机数去生成民名字)(没有写)
servlet中的写法,上传文件一定要是post
InputStream input=null;
File outFile=null;
FileOutputStream output=null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy//MM//dd//hh//mm//ss");
try{
pathdir = request.getPart("pathDir");
String filename=getFilename(pathdir);
String typename=getTypename(filename);
String file=filename.substring(0,filename.indexOf("."));
input =pathdir.getInputStream();
outFile=new File("e://"+sdf.format(new Date())+"//"+file+typename);
outFile.getParentFile().mkdirs();
outFile.createNewFile();
output=new FileOutputStream(outFile);
byte[] b=new byte[30];
while ( input.read(b)!=-1) {
output.write(b);
}
}catch(IOException e){
}finally{
if (input!=null) {
input.close();
}
if (output!=null) {
output.close();
}
}
jsp中
<form action="path" method="post" enctype="multipart/form-data">
<input type="file" name="pathDir" />
<input type="submit" id="subPath" value="上传" />
</form>