(100分)悬赏 Struts1.2 上传图片怎么得到上传时的文件夹的相对路径

来源:百度知道 编辑:UC知道 时间:2024/05/15 11:51:52
我上传时用的是绝对路很 本机可以访问 可是换了一个机子 能上传成功可就是看不到图片 我想用相对路径来解决这个问题 为了更好的移植

代码如下:
public ActionForward upLoad(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {

String path="error";
UpFileForm upForm = (UpFileForm) form;
FormFile file =upForm.getFormFile();
String oldName = file.getFileName();
String newName = Tool.getName()+"."+oldName.substring(oldName.lastIndexOf(".")+1,oldName.length());
String ipath=(this.getServlet().getServletContext().getRealPath("images\\")+"\\"+newName);
try {
InputStream strm = file.getInputStream();
FileOutputStream fos = new FileOutputStream(ipath);
int byt = 0;
byte b[] = new byte[8192];
while ((byt = strm.read(b,0,8192)) != -1) {
fos.write(b,0,byt);
}
fos.flush();
fos.close();
strm.close();

上传应该没有问题,可能是显示图片的部分有问题.

显示图片时不要使用这个getRealPath,只需要在页面通过
<img src="${pageContext.request.contextPath}/image/文件名">
就可以看到图片了

int start=ipath.lastIndexOf("\\");
ipath=ipath.subString(start+1);