您的位置:首页 > 编程语言 > Java开发

struts2中上传文件的实现

2017-06-01 17:18 302 查看
这里默认你的ssh的环境是整合好的,同时利用struts2里面封装好的东西来上传。

第一:建立一个FileImage的工具包类,里面的东西固定,若是不知道,可以去看struts2的upload拦截器。
代码如下:


import java.io.File;
public class FileImage {

private File file;

private String contentType;

private String filename;

//set必须固定,这是struts决定的,但是get方法是从action拿取的

public File getFile() {
return file;
}

public String getContentType() {
return contentType;
}

public String getFilename() {
return filename;
}

public void setUpload(File file){
this.file = file;
}

public void setUploadContentType(String contentType){
this.contentType = contentType;
}

public void setUploadFileName(String filename){
this.filename = filename;
}
}


第二:在action中


protected FileImage fileImage;


并且生成get和set方法

第三:service中就不说了,action中的save方法


public void save() throws Exception{
//实现文件上传的功能,然后把生生的uuid文件名交给pic。然后上传入库
//获取文件的后缀
String ext = FilenameUtils.getExtension(getFileImage().getFilename());
//这个工具类是本身包具有的
FileUtil.copyFile(getFileImage().getFile(),new File("f:/"+ UUID.randomUUID().toString()+"."+ext));
System.out.println(model);
}


第四:前端页面


<div>
<!-- ognl 表达式 fileImage.upload。 fileImage是一个属性 找setUpload方法就是。upload -->
<label>图片上传:</label> <input type="file" name=" fileImage.upload" />
</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts2.0