fileupload控件上传文章(分享fileupload获取文件路径)

一、什么是fileUpload?

fileUpload是apache的commons组件提供的上传组件,它最主要的工作就是帮我们解析request.getInpustream()。可以参考在线API文档:http://tool.oschina.net/apidocs/apidoc?api=commons-fileupload

二、fileupload组件工作原理

fileupload控件上传文章(分享fileupload获取文件路径)

2.编写jsp

fileupload控件上传文章(分享fileupload获取文件路径)

3.编写servlet

//创建业务层对象

NewsService newsService = new NewsService();

InputStream in = null;

OutputStream out = null;

int id = 0;//页面传来的id值

//创建解析器工厂

DiskFileItemFactory factory = new DiskFileItemFactory();

//获取解析器

ServletFileUpload upload = new ServletFileUpload(factory);

// 上传表单是否为multipart/form-data类型

if(!upload.isMultipartContent(request)) {

return ;

}

//解析request的输入流

try {

List<FileItem> parseRequest = upload.parseRequest(request);

//迭代list

for(FileItem f:parseRequest) {

if(f.isFormField()) {

//普通字段

id = Integer.parseInt(f.getFieldName());

String value = f.getString();

System.out.println(“name”+”=”+value);

}else {

//上传文件

//获取上传文件名

String name = f.getName();

System.out.println(“文件名”+name);

name = name.substring(name.lastIndexOf(“\”)+1);

System.out.println(name);

//获取输入流

in = f.getInputStream();

//获取上传文件路径

String savePath = “D:\workspacedt91\FileUpLoadTestDemo\WebContent\images\”+name;

//上传文件名若不存在, 则先创建

File path = new File(savePath);

if(!path.exists()) {

path.getParentFile().mkdir();

}

//获取输出流

out = new FileOutputStream(path);

int len = 0;

byte[] b = new byte[1024];

while((len = in.read(b)) > 0) {

out.write(b,0,len);

}

System.out.println(“上传成功”);

//保存到数据库

int count = newsService.saveUrl(name, id);

if(count > 0 ) {

System.out.println(“路径保存成功”);

}else {

System.out.println(“路径保存失败”);

}

}

}

} catch (FileUploadException e) {

// TODO Auto-generated catch block

System.out.println(“上传失败”);

e.printStackTrace();

}finally {

if(in != null) {

in.close();

}

if(out != null) {

out.close();

}

}

(0)
小多多的头像小多多创始人

相关推荐

发表回复

登录后才能评论