import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import javax.servlet.http.HttpServletResponse; import land.constant.FileConstant; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class UploadFile { private static final int BUFFER_SIZE = 1024;// 缓存区大小 // 上传单张图片 // 把图片文件上传到指定的目录 public static boolean copy(File src, File dst) { boolean isSuccess = false; try { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; while (in.read(buffer) > 0) { out.write(buffer); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } isSuccess = true; } catch (Exception e) { isSuccess = false; e.printStackTrace(); } return isSuccess; } // 获得文件后缀名 public static String getExtention(String fileName) { int pos = fileName.lastIndexOf("."); return fileName.substring(pos); } // 上传多张图片 public static String upload(File uploadify, String uploadifyFileName) { /* 文件扩展名 */ String extName = ""; /* 文件保存的位置 */ String saveRealFilePath = ""; /* * 相对路径,虚拟目录配置 <Context path="/images" docBase="相对路径[项目位置]"></Context> * 浏览器访问图片的路径是images/xx.jpg 实际存放路径是docBase */ saveRealFilePath = ServletActionContext.getServletContext() .getRealPath(FileConstant.FILE_PATH); /* * 绝对路径, 虚拟目录配置 <Context path="/images" docBase="绝对路径"></Context> * 浏览器访问图片的路径是images/xx.jpg 实际存放路径是docBase */ /* saveRealFilePath = "D:\\upload"; */ File fileDir = new File(saveRealFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } File savefile; if (uploadifyFileName.lastIndexOf(".") >= 0) { extName = uploadifyFileName.substring(uploadifyFileName .lastIndexOf(".")); } String nowTime = "" + new Date().getTime(); savefile = new File(saveRealFilePath, nowTime + extName); try { FileUtils.copyFile(uploadify, savefile); } catch (Exception e) { e.printStackTrace(); } HttpServletResponse response = ServletActionContext.getResponse(); try { response.getWriter().print(nowTime + extName); } catch (IOException e) { e.printStackTrace(); } return nowTime+extName; } public static boolean deleteFile(String filename) { boolean isSuccess = false; File imageFile = new File(ServletActionContext.getServletContext() .getRealPath(FileConstant.FILE_PATH) + "/" + filename); if (imageFile.exists()) { imageFile.delete(); isSuccess = true; } return isSuccess; } }