各位大大们,本人菜鸟一枚。现在用fileupload做上传图片的jsp网站,用servlet处理上传,把图片传到远程服务器,并把图片的显示路径写到数据库里。现在搞不懂这两个路径怎么写。上传的路径(服务器的路径)怎么获取,存到数据库里的路径又是什么,肯定不是服务器的路径吧。
解决方案 »
- jsp中两小参数同时传递?
- 大姐求助:帮我看看这段代码哪里不对了,为什么执行起来占内存过1G,而且特别慢,我只是提几个记录出来。我是在JBOSS下运行的
- 求救 Servlet 调用出问题了 急!
- 各位高手大家好!帮小妹解决一个的奇怪问题!
- 找大侠帮忙
- setBinaryStream()问题,急啊,谢谢
- 我的机器为什么装不上 Microsoft Visual SourceSafe 6.0 啊???????????
- tomcat项目部署后running为false,无法启动
- 求助:tomcat根据ip地址设置访问文件权限。
- 我使用jbuilder6.0来开发jsp,出现乱码怎么办????急急急!
- SSH
- JBPM问题,困我一天了,希望大家帮助下
数据库中存放的路径就是你把图片上传到服务端的路径。
服务端路径 request.getContextPath() + "";//引号中写入你tomcat中存放图片的相对路径,比如放在Web_Root下的upload文件夹中。request.getContextPath() + "//upload";
String filePath=this.getServletConfig().getServletContext().getRealPath("/");
String filePath2= filePath.replaceAll("\\\\","\\\\\\\\"); 数据库里写的路径就是图片的URL吧,就看你要怎么存了。
存在数据库里时你只存图片的名称,建议你写一个配置项。显示的时候就:配置项+图片名称。这样如果域名改变的话,你只要改一下配置项就可以了。如果把路径写到数据库里,域名改变时你就要把所有的http://www.photoupload.com都要更新成新的地址。有点麻烦。
大大们,赶紧帮我解决下,人家催着这几天要把网站上线,很急啊!就差这一个问题解决不了了。
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);
} // 保存上传的文件到指定的目录 // 在下文中上传文件至数据库时,将对这里改写 }
}
数据库中存放的路径就是你把图片上传到服务端的路径。
另外我在dopost里试了上面的所有方法,能成功的都是输出相对路径,不是绝对路径。