upload.jsp
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="com.ibm.zbc.UpFile" %>
<html> 
  <body>
   <form action="/test/Picser" method="post" ENCTYPE="multipart/form-data">
    <input type=file name="boy" size="45">
    <input type="submit" name="g" value="提交">
   </form>
 <br>
  </body>
</html>Picser-----servlet文件package com.ibm.zbc;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import mybean.data.UploadFile;import com.zbc.link.Dbconnection;
public class Picser extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
         


 String logname="lenovo";
UploadFile upFile=new UploadFile();

    //String fileName=null;
Dbconnection c9=new Dbconnection();
Connection con=null;
Statement stmt=null;
ResultSet rs=null;


try{

con=c9.getconn();

HttpSession session=request.getSession(true);
String tempFileName=(String)session.getId();
File f1=new File(tempFileName);
   FileOutputStream o=new FileOutputStream(f1);
   InputStream in=request.getInputStream();
   byte b[]=new byte[10000];
   int n;
   while((n=in.read(b))!=-1)
   {
   
 o.write(b, 0, n);  
   
   }
    
   o.close();
   in.close();
   RandomAccessFile random=new RandomAccessFile(f1, "r");
   int second=1;
   String secondLine=null;
   while(second<=2)
   {
   
   
   
   secondLine=random.readLine();
   second++;
   }
   int position=secondLine.lastIndexOf('\\');
 String fileName=secondLine.substring(position+1,secondLine.length()-1);
   byte cc[]=fileName.getBytes("ISO-8859-1");
   fileName=new String(cc);
   System.out.println(fileName);
   fileName=fileName.replaceAll(" ", "");
   String checkedStr=fileName.substring(0, fileName.indexOf("."));
   boolean isLetterOrDigit=true;
  for(int i=0;i<checkedStr.length();i++)
   {
   char c=checkedStr.charAt(i);
   if(!((c<='z'&&c>='a')||(c<='Z'&&c>='A')||(c<='9'&&c>='0')))
   {
  
  isLetterOrDigit=false;
  break;
  
  
  
   }
   
   
   
   
   }
   
  if(isLetterOrDigit==false)
   {
   
   response.sendRedirect("upload.jsp");
   
   
   
   }
   String savedFileName=logname.concat(fileName);
   random.seek(0);
   
   

   
   long forthEndPosition=0;
   int forth=1;
   while((n=random.readByte())!=-1&&(forth<=4))
   {
   if(n=='\n')
   {
   forthEndPosition=random.getFilePointer();  
   
   forth++; 
   } 
   }
   File dir=new File("E:/coding/Apache Software Foundation/Tomcat 7.0/webapps/test/img1");
   dir.mkdir();
   File file[]=dir.listFiles();
   for(int k=0;k<file.length;k++)
   {
 if(file[k].getName().startsWith(logname))  
 file[k].delete();
   
   
   
   }
   
   File savingFile=new File(dir,savedFileName);
  
   
   
   
   RandomAccessFile random2=new RandomAccessFile(savingFile,"rw");
   random.seek(random.length());
   long endPosition=random.getFilePointer();
   long =endPosition;
   int j=1;
   while((>=0)&&(j<=6))
   {
--;
random.seek();
n=random.readByte();
if(n=='\n');
{
endPosition=random.getFilePointer();
j++;
}
  }
   random.seek(forthEndPosition);
   long startPoint=random.getFilePointer();
   while(startPoint<endPosition-1)
   {
   
  n=random.readByte();
  random2.write(n);
  startPoint=random.getFilePointer();
   }
   random2.close();
   random.close();
  
       

stmt=con.createStatement();
stmt.executeUpdate("update tpictable set pic='"+savedFileName+"' where logname='"+logname+"'");

upFile.setFileName(fileName);
upFile.setSavedFileName(savedFileName);

 
 f1.delete();
 request.setAttribute("upFile", upFile);
 request.getRequestDispatcher("showUploadMess.jsp").forward(request,response);  
 return;

}
catch(ServletException e)
{
e.printStackTrace();
}
   catch(IOException e)
   {
   
   
   e.printStackTrace();
   
   }
   catch(ClassNotFoundException e)
   {
  e.printStackTrace(); 
   
   
   
   }
 catch(SQLException e)
 {
 
 e.printStackTrace();
 
 }
  

}
 
}

shoeUploadMess.jsp<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="mybean.data.UploadFile" %>
<%request.setCharacterEncoding("gb2312"); %>
<jsp:useBean id="upFile" type="mybean.data.UploadFile" scope="request"/><html>
  <head>
   
  </head>
  
  <body>
  
   <jsp:getProperty property="upFile" name="fileName"/>
    <jsp:getProperty property="upFile" name="savedFileName"/>
    <img src=img1/<jsp:getProperty property="upFile" name="savedFileName"/> width=150 height=120>hello!</img>
  </body>
</html>
首先,upload.jsp 文件上传文件,并提交给Picser,经过处理后在shoeUploadMess.jsp显示图片。
但就是传不过去,且异常,各位朋友们你们能伴我解决一下吗?谢谢!!!!!!JSP图片上传数据库

解决方案 »

  1.   

    action :
    package com.zlp.action;import java.io.File;
    import java.io.IOException;import org.apache.struts2.ServletActionContext;
    import org.aspectj.util.FileUtil;import com.opensymphony.xwork2.Action;
    import com.opensymphony.xwork2.ActionContext;public class FiltsuploadAction implements Action{
    private File[] image;
    private String[] imageFileName; // 命名规则
    private String[] imageContentType; public String execute() throws IOException {
    String filepath = ServletActionContext.getServletContext().getRealPath(
    "/images");

    System.out.println(filepath);
    if (image != null) {
    File savedir = new File(filepath);
    if(!savedir.exists()){
    savedir.mkdir();
    }
    //String fileName="";
    for (int i = 0; i < image.length; i++) {
    File destfile = new File(savedir, imageFileName[i]);
    FileUtil.copyFile(image[i], destfile);
    //fileName+=imageFileName[i];
    // ActionContext.getContext().put("message",
    //  fileName+ "文件上传成功");
    }
    }
    return SUCCESS;
    } public File[] getImage() {
    return image;
    }
    public void setImage(File[] image) {
    this.image = image;
    }
    public String[] getImageFileName() {
    return imageFileName;
    }
    public void setImageFileName(String[] imageFileName) {
    this.imageFileName = imageFileName;
    }
    public String[] getImageContentType() {
    return imageContentType;
    }
    public void setImageContentType(String[] imageContentType) {
    this.imageContentType = imageContentType;
    }}
    index.jsp:
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib uri="/struts-tags" prefix="s" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        
        
        <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
      </head>
      
      <body>
        
         <s:form action="FiltsuploadAction.action" method="post" enctype="multipart/form-data" namespace="/">
                <s:file name="image" label="文件1" ></s:file>
    <s:file name="image" label="文件2" ></s:file>
    <s:file name="image" label="文件3" ></s:file>
    <s:submit value="上传"/>
         </s:form>
      </body>
    </html>
    upload.jsp:
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'upload.jsp' starting page</title>
        
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->  </head>
      
      <body>
        <h1>上传成功</h1>
      </body>
    </html>
      

  2.   

    谢谢你的回答,如果不用struts2呢
      

  3.   

    现在有个问题。你是不是在debug环境下取不到图片????如果是的话你发布到tomcat下试试看。你保存文件不应该指定固定的路径,应该是相对于web程序的。