jsp部分的代码:
<s:form action="messageInfo-addMessage" enctype="multipart/form-data" method="post">
<s:file label="上传文章缩略图" name="photo" id="file_url" />
</s:form>
action部分的代码:
private File photo;
private String photoContentType;
private String photoFileName;
public File getPhoto() {
return photo;
}
public void setPhoto(File photo) {
this.photo = photo;
}
public String getPhotoContentType() {
return photoContentType;
}
public void setPhotoContentType(String photoContentType) {
this.photoContentType = photoContentType;
}
public String getPhotoFileName() {
return photoFileName;
}
public void setPhotoFileName(String photoFileName) {
this.photoFileName = photoFileName;
}
public String addMessage(){
System.out.println(photo);
System.out.println(photoContentType);
System.out.println(photoFileName);
String extName = photoFileName.substring(photoFileName.lastIndexOf("."));
String path = "/uploadimg/"+System.currentTimeMillis()+extName;
String realPath = ServletActionContext.getServletContext().getRealPath(path);
messageInfo.setThumb(path);
try {
System.out.println("这里是try,catch");
FileUtils.copyFile(photo, new File(realPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(path);
System.out.println(realPath);
System.out.println("132");
return "addMessage";
}
要注意的是,action定义的三个变量photo,photoContentType
,photoFileName.三个变量。前面的photo对应的是JSP页面的文本框的name。后部分ContentType,FileName. 则分别获取到的是所传文件的类型以及所传文件的名字。
另外,上传的文件不会显示到eclipse里面的所建立的文件夹,它是被传到了相当于tomcat目录下的工程所对应的文件夹下,所有上传完毕之后是不会在eclipse里面的文件夹里看到的