java简单文件上传

来源:互联网 发布:科荣软件 编辑:程序博客网 时间:2024/06/04 08:03
public static void doUpload(File file,String path, String name) throws Exception {
if(null == file){
throw new Exception();
}

// 基于file创建一个文件输入流
InputStream is = new FileInputStream(file);


// 设置上传文件目录
//String uploadPath = ServletActionContext.getServletContext().getRealPath("/") + path;

File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}

// 设置目标文件
File toFile = new File(path, name);

// 创建一个输出流
OutputStream os = new FileOutputStream(toFile);


// 设置缓存
byte[] buffer = new byte[1024];


int length = 0;


try {
// 读取myFile文件输出到toFile文件中
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (IOException e) {
e.getMessage();
} finally {
// 关闭输入流
if (null != is) {
is.close();
}
// 关闭输出流
if (null != os) {
os.close();
}
}
}
0 0
原创粉丝点击