您的位置:首页 > 编程语言 > Java开发

java简单文件上传

2016-01-28 14:24 363 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: