ssh实现文件上传用到 commons-fileupload-1.3.1.jar, commons-io-2.2.jar这两个包
实现上传功能的页面代码
<h1>上传文件</h1> <form action="upLoadFile" method="post" enctype="multipart/form-data"> <input type="file" value="选择文件" name="upload"> <input type="submit" value="长传文件" > </form>这段代码有三个地方需要注意
1. method 需要设置成post 因为get有长度的限制,所以用get一些稍大的文件无法上传
2 在form中添加这段代码
enctype="multipart/form-data"3 需要有一个input的type=‘file’
struts.xml中的代码是
<!-- 上传的文件的默认大小是不能超过2M(2097152) 如果超过会报错。这段代码用于修改默认大小 --> <constant name="struts.multipart.maxSize" value="20971520"/> <package name="default" extends="struts-default" namespace="/"> <action name="upLoadFile" class="userAction"> <!-- 当文件上传成功 跳转到success.jsp --> <result name="success">success.jsp</result> <!-- 当文件上传失败 跳转到error.jsp --> <result name="input">error.jsp</result> <interceptor-ref name="defaultStack"> <!-- 用与设置上传文件的类型 --> <param name="fileUpload.allowedExtensions">.jpg,.txt</param> </interceptor-ref> </action> </package>action中的关键代码
public class UserAction extends ActionSupport implements ModelDriven<User>{ private UserService userService; // 通过注入获取userService 用于操作数据库 public void setUserService(UserService userService) { this.userService = userService; } // 上传的文件 // 这是 index.jsp 中的代码 <input type="file" value="选择文件" name="upload"> // 这两个 upload 名字需要一样 private File upload; // 表示上传文件文件的名字 必须这么写 private String uploadFileName; // 表示上传文件文件的MIME类型 必须这么写 private String uploadContentType; // 设置三个属性的 set方法 struts将三个值注入 就可以直接使用 public void setUpload(File upload) { this.upload = upload; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } User user=new User(); public User getModel() { return user; } public String execute() throws Exception { if(uploadFileName != null){ // 防止用户传入文件的名字冲突 对文件的名字进行处理 String newFileName=UpLoadFileUtils.getUUidFileName(uploadFileName); // 自定义传入文件存放的位置 String path="D:\\images\\"; // 创建新的文件 File file=new File(path+newFileName); // 通过拷贝 达到存储文件的目的 FileUtils.copyFile(upload, file); // 将存储的文件的路径存入数据库 方便以后使用 user.setPath(path+newFileName); userService.save(user); } return SUCCESS; } } 用于处理文件名字的方法 public class UpLoadFileUtils { public static String getUUidFileName(String fileName){ int lastIndexOf = fileName.lastIndexOf("."); String lastName = fileName.substring(lastIndexOf,fileName.length()); String uuid=UUID.randomUUID().toString().replace("-", ""); return uuid+lastName; } }这个是完整例子 百度云链接 密码:ksse 如果有错的地方欢迎指出