package cn.com.ajaxbear.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.UUID; import org.apache.struts2.ServletActionContext; import cn.com.ajaxbear.util.XResponse; public class UploadAction extends BaseAction { private File upload; private String uploadContentType; public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } // 上传文件的文件名 private String uploadFileName; private String getFileExp(String name){ int pos = name.lastIndexOf("."); return name.substring(pos); } @Override public String execute() throws Exception { //首先判断用户是否曾经上传过,如果上传过,则删掉原来的文件(这里我没考虑其他情况,考虑周全还要写一些代码) String oldImageName = request.getParameter("oldImageName"); //如果存在则删除 if (!"noImage".equalsIgnoreCase(oldImageName)) { File oldFile = new File(ServletActionContext .getServletContext().getRealPath("/") + "UploadImages" + File.separator+oldImageName); oldFile.delete(); } System.out.println(oldImageName); //为用户新上传的图片新取一个名字 String newName = UUID.randomUUID().toString(); //获取用户上传的图片格式 String exp = getFileExp(uploadFileName); //将文件写入文件夹 FileOutputStream fos = new FileOutputStream(ServletActionContext .getServletContext().getRealPath("/") + "UploadImages" + File.separator + newName+exp); FileInputStream fis = new FileInputStream(upload); byte[] buffer = new byte[10240]; int len = 0; int total = fis.available(); System.out.println("文件大小为:"+total); while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); fos.flush(); } fis.close(); fos.close(); //返回图片名称(路径我是在前台写死了的),注意返回的contentType不能是text/json; XResponse.sendMSG(response, "{success : true,msg:'"+newName+exp+"'}","text/html; charset=utf-8"); return NONE; } }