标题:Javaweb中上传图片,获取相对路径,绝对路径
实际上获取的是绝对路径,不过通过浏览器查看到的不会是绝对路径,而是被浏览器保护好,给你看到的一个假的路径,而我们要做的就是获取图片的名字即可,人为的添加一个路径,同时写入到数据库中一个相对路径即可
最后的图片保存的绝对路径【不是图片原来的绝对路径】,
E:\eclipse\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\itcaststore\productImg\11\1
相对路径【数据库中使用相对路径,使得可以在浏览器中显示图片,而使用绝对路径,在浏览器中显示不了图片,只能在eclipse中的内置浏览器中显示图片】:
/productImg/11/1/fec068b5-afd0-4d45-b31b-0f7cddf4f25b.jpg
具体操作:
package cn.itcast.itcaststore.web.servlet.manager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import cn.itcast.itcaststore.domain.Product;
import cn.itcast.itcaststore.exception.AddProductException;
import cn.itcast.itcaststore.service.ProductService;
import cn.itcast.itcaststore.utils.FileUploadUtils;
import cn.itcast.itcaststore.utils.IdUtils;
/**
* 后台系统
* 用于添加商品的servlet
*/
public class AddProductServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 创建javaBean,将上传数据封装.
Product p = new Product();
Map<String, String> map = new HashMap<String, String>();
// 封装商品id
map.put("id", IdUtils.getUUID());
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 设置临时文件存储位置
dfif.setRepository(new File(this.getServletContext().getRealPath(
"/temp")));
// 设置上传文件缓存大小为10m
dfif.setSizeThreshold(1024 * 1024 * 10);
// 创建上传组件
ServletFileUpload upload = new ServletFileUpload(dfif);
// 处理上传文件中文乱码
upload.setHeaderEncoding("utf-8");
try {
// 解析request得到所有的FileItem
List<FileItem> items = upload.parseRequest(request);
// 遍历所有FileItem
for (FileItem item : items) {
// 判断当前是否是上传组件
if (item.isFormField()) {
// 不是上传组件
String fieldName = item.getFieldName(); // 获取组件名称
String value = item.getString("utf-8"); // 解决乱码问题
map.put(fieldName, value);
} else {
// 是上传组件
// 得到上传文件真实名称
String fileName = item.getName();
fileName = FileUploadUtils.subFileName(fileName);
// 得到随机名称
String randomName = FileUploadUtils
.generateRandonFileName(fileName);
// 得到随机目录
String randomDir = FileUploadUtils
.generateRandomDir(randomName);
// 图片存储父目录
String imgurl_parent = "/productImg" + randomDir;
File parentDir = new File(this.getServletContext()
.getRealPath(imgurl_parent));
// 验证目录是否存在,如果不存在,创建出来
if (!parentDir.exists()) {
parentDir.mkdirs();
}
String imgurl = imgurl_parent + "/" + randomName;
map.put("imgurl", imgurl);
IOUtils.copy(item.getInputStream(), new FileOutputStream(
new File(parentDir, randomName)));
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
try {
// 将数据封装到javaBean中
BeanUtils.populate(p, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
ProductService service = new ProductService();
try {
// 调用service完成添加商品操作
service.addProduct(p);
response.sendRedirect(request.getContextPath()
+ "/listProduct");
return;
} catch (AddProductException e) {
e.printStackTrace();
response.getWriter().write("添加商品失败");
return;
}
}
}
<%@ page language="java" pageEncoding="UTF-8"%>
<HTML>
<HEAD>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<LINK href="${pageContext.request.contextPath}/admin/css/Style.css" type="text/css" rel="stylesheet">
</HEAD>
<body>
<form id="userAction_save_do" name="Form1"
action="${pageContext.request.contextPath}/addProduct" method="post"
enctype="multipart/form-data">
<table cellSpacing="1" cellPadding="5" width="100%" align="center"
bgColor="#eeeeee" style="border: 1px solid #8ba7e3" border="0">
<tr>
<td class="ta_01" align="center" bgColor="#afd1f3" colSpan="4"
height="26"><strong><STRONG>添加商品</STRONG> </strong>
</td>
</tr>
<tr>
<td align="center" bgColor="#f5fafe" class="ta_01">商品名称:</td>
<td class="ta_01" bgColor="#ffffff"><input type="text" name="name" class="bg" /></td>
<td align="center" bgColor="#f5fafe" class="ta_01">商品价格:</td>
<td class="ta_01" bgColor="#ffffff">
<input type="text" name="price" class="bg" />
</td>
</tr>
<tr>
<td align="center" bgColor="#f5fafe" class="ta_01">商品数量:</td>
<td class="ta_01" bgColor="#ffffff">
<input type="text" name="pnum" class="bg" />
</td>
<td align="center" bgColor="#f5fafe" class="ta_01">商品类别:</td>
<td class="ta_01" bgColor="#ffffff">
<select name="category" id="category">
<option value="" selected="selected">--选择商品类加--</option>
<option value="文学">文学</option>
<option value="生活">生活</option>
<option value="计算机">计算机</option>
<option value="外语">外语</option>
<option value="经营">经营</option>
<option value="励志">励志</option>
<option value="社科">社科</option>
<option value="学术">学术</option>
<option value="少儿">少儿</option>
<option value="艺术">艺术</option>
<option value="原版">原版</option>
<option value="科技">科技</option>
<option value="考试">考试</option>
<option value="生活百科">生活百科</option>
</select>
</td>
</tr>
<tr>
<td align="center" bgColor="#f5fafe" class="ta_01">商品图片:</td>
<td class="ta_01" bgColor="#ffffff" colspan="3">
<input type="file" name="upload" size="30" value="" />
</td>
</tr>
<TR>
<TD class="ta_01" align="center" bgColor="#f5fafe">商品描述:</TD>
<TD class="ta_01" bgColor="#ffffff" colSpan="3">
<textarea name="description" cols="30" rows="3" style="WIDTH: 96%"></textarea>
</TD>
</TR>
<TR>
<td align="center" colSpan="4" class="sep1"><img
src="${pageContext.request.contextPath}/admin/images/shim.gif">
</td>
</TR>
<tr>
<td class="ta_01" style="WIDTH: 100%" align="center"
bgColor="#f5fafe" colSpan="4">
<input type="submit" class="button_ok" value="确定">
<FONT face="宋体"> </FONT>
<input type="reset" value="重置" class="button_cancel">
<FONT face="宋体">
</FONT>
<INPUT class="button_ok" type="button" onclick="history.go(-1)" value="返回" />
<span id="Label1"></span>
</td>
</tr>
</table>
</form>
</body>
</HTML>