cd86254081 2015-07-04 14:22 采纳率: 100%
浏览 1621
已采纳

上传图片和音乐的路径问题

代码如下:

private static final long serialVersionUID = 572146812454L;
private File image; // 上传的文件
private String imageFileName; // 文件名称
private String imageContentType; // 文件类型
User user = (User) ActionContext.getContext().getSession().get("user");
private HttpServletResponse response = ServletActionContext.getResponse();
private HttpServletRequest request = ServletActionContext.getRequest();

private List picList;

public List getPicList() {
return picList;
}

public void setPicList(List picList) {
this.picList = picList;
}

private String picId;

private String userId;

private String commentPic;

//省略getter和setter

public String uploadPicture() throws IOException {
String s = UUID.randomUUID().toString();
String lastName = imageFileName.substring(imageFileName
.lastIndexOf(".") + 1, imageFileName.length());
String name = s + "." + lastName;
username = user.getUsername();
//获取服务器路径
String realpath = ServletActionContext.getServletContext().getRealPath(
"/upload");
System.out.println("realpath: " + realpath);
if (image != null) {
File savefile = new File(new File(realpath), name);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
String imagePath = "/sDemo/upload/" + name;
System.out.println("imagePath: " + imagePath);
Picture picture = new Picture();
picture.setUserId(user.getId());
picture.setUserName(user.getUsername());
picture.setPictureUrl(imagePath);
ser.insertPicture(picture);
}
return "upload";
}

我想知道 String realpath = ServletActionContext.getServletContext().getRealPath("/upload");里"/upload"是干什么的?和 String imagePath = "/sDemo/upload/" + name;里的upload有关系吗?
我用这个上传图片上传了一张图片,但是在imagepath路径下并没有看到图片,是存到了realpath下吗?既然这样为什么要将url=imagepath存入数据库而不是存realpath?
上传的图片是不是实际上存在tomcat上的realpath下,通过imagepath存取?这两个路径之间通过什么建立关系?读取图片的时候读取<img src="${pictureUrl}"就可以吗。读取音乐的时候是不是一样的方式?

  • 写回答

3条回答

  • 全栈极简 博客专家认证 2015-07-04 14:28
    关注

    realpath是实际路径,文件上传时需要这个完整的路径才能知道传到哪。
    imagePath这个只是保存到数据库的路径,由于是服务器端,我们只要知道在当前站点根目录下的路径即可。由于是相对路径,项目中引用图片显示的时候,可以直接用这个路径。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算