各位大大们,本人菜鸟一枚。现在用fileupload做上传图片的jsp网站,用servlet处理上传,把图片传到远程服务器,并把图片的显示路径写到数据库里。现在搞不懂这两个路径怎么写。上传的路径(服务器的路径)怎么获取,存到数据库里的路径又是什么,肯定不是服务器的路径吧。

解决方案 »

  1.   

    request.getRealPath("/")+"定义好的路径"
    数据库中存放的路径就是你把图片上传到服务端的路径。
      

  2.   

    客户端路径(图片的本地路径):即图片的绝对路径。
    服务端路径 request.getContextPath() + "";//引号中写入你tomcat中存放图片的相对路径,比如放在Web_Root下的upload文件夹中。request.getContextPath() + "//upload";
      

  3.   

                
    String filePath=this.getServletConfig().getServletContext().getRealPath("/");
    String filePath2=  filePath.replaceAll("\\\\","\\\\\\\\");       数据库里写的路径就是图片的URL吧,就看你要怎么存了。
      

  4.   

    这么说吧,比如我有个域名www.photoupload.com,现在网站已经放到买来的服务器空间里,我要把图片上传到这个服务器我网站根目录下的/photo文件夹里,用servlet获取服务器的路径,作为我的上传路径,另外还要把图片的路径存到数据库里,要在网站上能显示出来我上传的图片。有人说上传路径就是服务器的真实物理路径,而存到数据库的路径是http://www.photoupload.com/photo/123.jpg这样。到底是不是这样。如果是这样,在servlet里获取服务器路径怎么写,如果不是这样,那上传路径和存到数据库的路径又是怎么写。请给个真实能用的答案。上面的回答我试了不行啊!
      

  5.   

    上传图片时绝对路径在servlet中用request.getRealPath("/")+"你放图片的目录"
    存在数据库里时你只存图片的名称,建议你写一个配置项。显示的时候就:配置项+图片名称。这样如果域名改变的话,你只要改一下配置项就可以了。如果把路径写到数据库里,域名改变时你就要把所有的http://www.photoupload.com都要更新成新的地址。有点麻烦。
      

  6.   

    String filePath=request.getRealPath("/");在servlet里是错的,本可以用request
      

  7.   

    String path=getServletContext().getRealPath( "/")+filePath;
      

  8.   

    angel21li的一看就知道是错的,getServletContext()方法不用对象或是类名来调用吗?
      

  9.   

    我用myEclipse写这条的时候提示不能处理request。我之前按别人的提示凡是写的request都是错的,request好像只能在jsp里面用。
      

  10.   

    angel21li说的也是对的。它是servlet中的一个内置对象方法。楼主把你写的servlet类贴出来看看。
      

  11.   


    大大们,赶紧帮我解决下,人家催着这几天要把网站上线,很急啊!就差这一个问题解决不了了。
    package com.travel.lvyou.servlet;import java.io.File;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.xml.ws.Response;
    import org.apache.commons.fileupload.*;
    import java.sql.Connection;
    import java.util.*;
    import java.util.regex.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import com.travel.lvyou.DB;public class FileUpload extends HttpServlet {

    String mypath = URLProducter.getProperty();//这是我目前的上传路径,是我电脑本地服务器,等我把网站上传以后,想获得远程服务器的路径
    String dbpath = URLProducter.getPropertydbpath();//这是我存入数据库的路径,目前也是我手写的//以下是从网上找的代码,菜鸟不太懂,只好引用别人的了,按我现在这个程序在本地上传是可以的。
    @Override
    public void init(ServletConfig config) throws ServletException {
    uploadPath = config.getInitParameter("uploadPath");
    System.out.println(uploadPath);

    } String uploadPath = "";

     @Override
    public void destroy() {
      super.destroy(); // Just puts "destroy" string in log
      // Put your code here
     }  /**
      * The doPost method of the servlet. <br>
      *
      * This method is called when a form has its tag value method equals to post.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
      @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
      
      int id = -1;
      int pid = -1;
      int uid = -1;
      String titlename = null;
      int inforid = -1;
      
      res.setContentType( "text/html; charset=GB2312");
      PrintWriter out=res.getWriter();
      System.out.println(req.getContentLength());
         System.out.println(req.getContentType());
       DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(4096);
            // the location for saving data that is larger than getSizeThreshold()
            factory.setRepository(new File(mypath));         ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum size before a FileUploadException will be thrown
            upload.setSizeMax(1000000);
            try{
            List fileItems = upload.parseRequest(req);
            // assume we know there are two files. The first file is a small
            // text file, the second is unknown and is written to a file on
            // the server
            Iterator iter = fileItems.iterator(); //  正则匹配,过滤路径取文件名
         String regExp=".+\\\\(.+)$";   //  过滤掉的文件类型
      String[] errorType={".exe",".com",".cgi",".asp"};
         Pattern p = Pattern.compile(regExp);
            while (iter.hasNext()) {
             FileItem item = (FileItem)iter.next();
             //忽略其他不是文件域的所有表单信息
             if(item.isFormField()){
             if(item.getFieldName().equals("id")){   
              
                 id = Integer.parseInt(item.getString().replaceAll("/", "/"));   
            
             } else  if(item.getFieldName().equals("pid")){
             pid = Integer.parseInt(item.getString().replaceAll("/", ""));
               }else  if(item.getFieldName().equals("uid")){                                    uid = Integer.parseInt(item.getString().replaceAll("/", ""));
                                        }else  if(item.getFieldName().equals("titlename")){
                                 titlename = item.getString().replaceAll("/", "/");
                                        }else  if(item.getFieldName().equals("inforid")){
     
             inforid = Integer.parseInt(item.getString().replaceAll("/", ""));
                                        }
                     
          }
             if (!item.isFormField()) {
                 String name = item.getName();
                 long size = item.getSize();
                 if((name==null||name.equals("")) && size==0)
                     continue;
              Matcher m = p.matcher(name);
              System.out.println(m);
             boolean result = m.find();
             System.out.println(result);
             if (result){
                 for (int temp=0;temp<errorType.length;temp++){
                 if (m.group(1).endsWith(errorType[temp])){
                       throw new IOException(name+": wrong type");
                 }
                 }
                 try{//         保存上传的文件到指定的目录//         在下文中上传文件至数据库时,将对这里改写
                
                         item.write(new File(mypath+ titlename + id + ".jpg"));
                         String imageurl = dbpath+ titlename + id + ".jpg";
                         Connection conn = DB.getConn();
                         String sql = null;
                         if(inforid == 12){
                          sql = "update Hainan set PhotoLinks"+ uid + " = '" + imageurl + "' where CityID = " + pid;
                         }else if (inforid == 22){
                          sql = "update China set PhotoLinks"+ uid + " = '" + imageurl + "' where NameID = " + pid;
                         }else if (inforid == 31 || inforid == 32 || inforid == 33 || inforid == 34 ||inforid == 35){
                          sql = "update Hotel set PhotoLinks"+ uid + " = '" + imageurl + "' where HotelID = " + pid;
                         }else if (inforid == 41 || inforid == 42 || inforid == 43 || inforid == 44){
                          sql = "update Sceneryspot set PhotoLinks"+ uid + " = '" + imageurl + "' where SceneryspotID = " + pid;
                         }else if (inforid ==101){
                          sql = "update Sceneryspot set PhotoLinks"+ uid + " = '" + imageurl + "' where SceneryspotID = " + pid;
                         }else if (inforid == 51 || inforid == 52 || inforid == 53){
                          sql = "update Golf set PhotoLinks"+ uid + " = '" + imageurl + "' where GolfID = " + pid;
                         }else if(inforid == 61 || inforid == 62 || inforid == 63 || inforid == 64 || inforid == 65 || inforid == 66){
                          sql = "update Restaurant set PhotoLinks = '" + imageurl + "' where RestaurantID = " + pid;
                         }else if(inforid == 71 || inforid == 72 || inforid == 73 || inforid == 74 || inforid == 75 || inforid == 76 ){
                          sql = "update HotSpring set PhotoLinks"+ uid + " = '" + imageurl + "' where HotSpringID = " + pid;
                         }else if(inforid == 81){
                          sql = "update NationalPark set PhotoLinks"+ uid + " = '" + imageurl + "' where NationalParkID = " + pid;
                         }
                         System.out.println(sql);
                         DB.executeUpdate(conn, sql);
                         
                         res.sendRedirect("../manage/update.jsp?id=" + inforid + "&pid=" + pid);
                         
                      /*   res.setContentType("text/html; charset=gb2312");                       ServletContext sc = getServletContext();                       RequestDispatcher rd = null;                       rd = sc.getRequestDispatcher("/index.jsp");       //定向的页面                       rd.forward(req, res); 
                        */
              
                       }
                       catch(Exception e){
                         out.println(e);
                       }                 }
                   else
                   {
                     throw new IOException("fail to upload");
                   }
                   }
               }
            }
             catch (IOException e){
               out.println(e);
               e.printStackTrace();
               e.getMessage();
               e.getStackTrace();
             }
             catch (FileUploadException e){
                  out.println(e);
             } //  保存上传的文件到指定的目录 //  在下文中上传文件至数据库时,将对这里改写     }
    }
      

  12.   

    你在doPost方法中用req.getRealPaht("/")+"图片路径"
      

  13.   

    上面的写错了应该是req.getRealPath("/")
      

  14.   

    request.getRealPath("/")+"定义好的路径"
    数据库中存放的路径就是你把图片上传到服务端的路径。
      

  15.   

    大错特错,一个网站怎么可能把图片等这些珍贵的数据放在WEB工程下,一般是放在库中,或者专门搞个 工作目录存放这些数据。然后在web.xml中设置param,在ContextListener实现类中查找这个目录并且有个专门的对象用来管理这个目录。
      

  16.   

    按你说的做出现这个错误:The method getRealPath(String) from the type ServletRequest is deprecated;
    另外我在dopost里试了上面的所有方法,能成功的都是输出相对路径,不是绝对路径。
      

  17.   

    String realPath = request.getSession().getServletContext().getRealPath("/");