1)上传图片upload_image.jsp页面
<body>
<s:form action="image/upload" method="post" enctype="multipart/form-data">
<s:file name="some" label="选择文件" />
<s:submit value="上传" method="upload"/>
</s:form>
</body>
2)Struts.xml配置文件
<package name="image" extends="struts-default" namespace="/image">
<action name="upload" class="com.zhongluo.zhaopinjiuye.action.company.UploadAction">
<result name="preUpload">
/upload_image.jsp
</result>
<result name="success">
/show_image.jsp
</result>
<result name="error">
/upload_image.jsp
</result>
</action>
</package>
3)UploadAction.java代码
public class UploadAction extends BaseAction{
int id;
String url;
private File some;
private String someFileName;
private String someContextType;
private String imagePath;
public String upload() throws Exception{
if(some==null){
return "error";
}
String imageName = "file_"+System.currentTimeMillis() +someFileName.substring(someFileName.lastIndexOf("."));
imagePath = "upload/" + imageName;
String realImagePath = ServletActionContext.getRequest().getRealPath(imagePath);
boolean b = copy(some, new File(realImagePath));
Image image = new Image();//数据库对应的bean,有主键id,String类型的url
image.setImageurl(realImagePath);
ImageService imageservice = (ImageService)getBeanFromCurrentContext("ImageService");
setId(imageservice.save(image));
setUrl(ServletActionContext.getRequest().getContextPath()+"/"+imagePath);
if(!b){
return "error";
}
return "success";
}
public static boolean copy(File src,File dest){
InputStream bis = null;
OutputStream bos = null;
try{
bis = new FileInputStream(src);
bos = new FileOutputStream(dest);
byte[] bts = new byte[1024];
int len = -1;
while((len=bis.read(bts))!=-1){
bos.write(bts,0,len);
}
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally{
if(bis!=null){
try{
bis.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(bos!=null){
try{
bos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
//相关属性get、set方法
}
4)显示图片show_image.jsp界面
<body>
<h1>
文件上传成功
</h1>
<div>
<img src='<s:property value="url"/>'/>
</div>
</body>