Struts2使用文件、图片上传工具类步骤:
准备工作:导入commons-io-2.0.1.jar和commons-fileupload-1.2.1.jar
1、 在前台input表单中必须将name属性设置为“image”
2、 在action中拷入如下代码:
/*****************以下为上传部分*******************************/
private File image; //得到上传的文件
private String imageFileName; //得到文件的名称,写法是固定的
private String imageContentType; //得到文件的类型
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String addUI(){
return SUCCESS;
}
3、 使用类似如下方法调用工具类
public String testUpload(){
String fileName = "imagesSave";
UploadFiles uploadFiles = new UploadFiles();
String path = uploadFiles.uploadPicture(fileName, imageFileName, image);
// = uploadPicture(fileName,imageFileName,image);
System.out.println("工具类的文件路径为:"+path);
return "upload";
}
4、 工具类为:
package ecp.util;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
/*****************以下为上传部分*******************************/
public class UploadFiles {
public String uploadPicture(String fileName,String imageFileName,File image){ //fileName为存放照片的文件夹名称,照片会存在tomcat路径的以你此时的传入的名称为名称的文件夹中
String picturePath = "";
HttpServletRequest request = ServletActionContext.getRequest();
//保存到根目录下的uploadImages文件夹下
String realPath = ServletActionContext.getServletContext().getRealPath("/"+fileName); //取得真实路径
System.out.println(realPath);
System.out.println(imageFileName);
//System.out.println(imageContentType);
//自动命名
Random random = new Random(99999);
int tempInt = random.nextInt();
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
int last = imageFileName.lastIndexOf(".");
String head = imageFileName.substring(0,last);
String type = imageFileName.substring(last);
imageFileName = simpleDateFormat.format(date) + tempInt + type;
System.out.println("新的文件名称是:"+imageFileName);
//创建父文件夹
if(image!=null){
File saveFile = new File(new File(realPath), imageFileName);
if(!saveFile.getParentFile().exists()){ //如果Images文件夹不存在
saveFile.getParentFile().mkdirs(); //则创建新的多级文件夹
}
try {
FileUtils.copyFile(image, saveFile); //保存文件
ActionContext.getContext().put("message", "上传成功!");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
picturePath = basePath +fileName+"/"+imageFileName;
} catch (IOException e) {
e.printStackTrace();
}
}
return picturePath;
}
}
Struts2文件和图片上传
最新推荐文章于 2019-08-29 09:40:03 发布