使用JSP or Servlet技术开发新闻发布系统(6)
上传文件:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
//试着去用request
String username = request.getParameter("username");
System.out.println(username);
System.out.println("---------------------------------------------------------");
//1.创建FileItemFactory对象
FileItemFactory factory = new DiskFileItemFactory();
//2.创建ServletFileUpload对象
ServletFileUpload upload = new ServletFileUpload(factory);
//3.解析request
//如果表单上设置enctype="multipart/form-data" 原来获取表单的值得方式 没有作用
//重新解析请求 将表单中所有的提交框体的内容 包装成了一个List
List<FileItem> list = upload.parseRequest(request);
Users u = new Users();
for(FileItem fi : list){
//判定非type=file的框体
if(fi.isFormField())
{
String formName = fi.getFieldName(); //name属性值
if("username".equals(formName))
{
u.setUsername(fi.getString("utf-8"));
}
}
else
{
//type="file"的内容
long size = fi.getSize();
System.out.println(size);
String name = fi.getName(); //文件名
System.out.println(name);
//1.获取项目的发布路径
ServletContext application = this.getServletContext();
String path = application.getRealPath("/");
System.out.println("path:"+path);
String dirPath = path+"image"; //图片文件夹的地址
//创建file对象
File dirFile = new File(dirPath);
if(!dirFile.exists())
{
dirFile.mkdir(); //创建文件夹
}
//图片的地址
String imgPath = dirPath+"\\"+name;
//保存在数据库的路径是
String savePath = "image/"+name;
u.setPhoto(savePath);
//读取上传图片
InputStream is = fi.getInputStream();
byte[] b = new byte[(int)size];
is.read(b, 0, b.length);
FileOutputStream fos = new FileOutputStream(imgPath);
fos.write(b);
fos.flush();
is.close();
fos.close();
}
}
usersDao.saveUsers(u);
request.setAttribute("user", u);
request.getRequestDispatcher("MyJsp.jsp").forward(request, response);
}
catch (FileUploadException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
必须用form form表单中的method必须设置为post
设置enctype="multipart/form-data"