***要正常实现文件上传以下步骤应该全部考虑到:
*1.html中
*2.form的enctype="multipart/form-data"
*3.在Servlet类前加上 @MultipartConfig
*4.request.getPart()获得上传文件对象 //request.getParameter();
以下代码全是从我的代码了复制过来的,没有花太多的时间整理,先看一下效果图吧
//下面代码是文件上传部分,功能主要是获取到上传图片的路劲和图片名称,然后上传图片,并把路径保存到数据库中
@WebServlet("/UploadImage")
@MultipartConfig
public class UploadImage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("---这里是上传个人图片的servlet----");
Part part = request.getPart("pic");
String file = part.getHeader("Content-Disposition");
//得到文件的名字
String fileName = file.substring(file.lastIndexOf("=")+2, file.length()-1);
System.out.println(fileName);
//获取部署的根目录
String basePath = getServletContext().getRealPath("/");
System.out.println(basePath);
//将文件上传到部署的根目录下
part.write(basePath+fileName);
//以下代码是对应我的项目的,可以修改为对应自己项目的代码
int id = Integer.parseInt(request.getParameter("updateId"));
OperaterImpl operaterImpl = new OperaterImpl();
OperaterEntity operaterEntity = operaterImpl.findById(id);
operaterEntity.setpicPath(basePath+fileName);
operaterImpl.update(operaterEntity);
response.getWriter().write("");
}
}
@WebServlet("/ShowImageSer")
public class ShowImageSer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从前台获取图片的路劲(部署项目的根路径)此路劲必须包含到图片,
//如D:\My\SOFTWORE\apache-tomcat-7.0.52\wtpwebapps\imas\111.gif
String picPath = request.getParameter("picpath");
//以该路劲创建一个新文件
File file = new File(picPath);
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));
System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));
OutputStream output = null;
FileInputStream fis = null;
try{
output = response.getOutputStream();
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b))!=-1){
output.write(b, 0, i);
}
output.write(b, 0, b.length);
output.flush();
response.flushBuffer();
}
catch(Exception e){
System.out.println("Error!");
e.printStackTrace();
}
finally{
if(fis != null){
fis.close();
fis = null;
}if(output != null){
output.close();
output = null;
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
//这是显示图片的区域,使用img标签,在src里面访问到servlet类(
ShowImageSer),并且传递图片路劲参数过去
picpath=<%=operaterEntity.getpicPath() %>">