1.html部分
<input style="width: 280px" type="file" name="upLoadProjectPlan" id="upLoadProjectPlan" value="<%=taskAppend.getTaskAllocationDoc()%>"/> <a style="float: right; margin-right: 40px" class="button" href="javascript:void(0)" onclick="UpladFile('upLoadProjectPlan', '<%=task.getTaskid() %>')"><span>上传</span></a>
2.js中利用ajax产生表单并发送表单
function UpladFile(fileUploadId, taskid) { var fileObj = document.getElementById(fileUploadId).files[0]; // 获取文件对象 var FileController = "updateWorkAction!fileUpload"; // 接收上传文件的后台处理程序地址 // FormData 对象 var form = new FormData(); //form.append("author", "hooyes"); // 可以增加表单数据 form.append("taskid", taskid); form.append("file", fileObj); // 文件对象 // XMLHttpRequest 对象 var xhr = new XMLHttpRequest(); xhr.open("post", FileController, true); xhr.onload = function () { location.reload(true); alert("上传完成!"); }; xhr.send(form); }
3.Action部分
public class UpdateWorkAction extends ActionSupport{ private DistributeDao distributeDao; private String taskid; private List<File> file; // 上传的文件 private List<String> fileFileName; // 文件名称 private List<String> fileContentType; // 文件类型 public DistributeDao getDistributeDao() { return distributeDao; } public void setDistributeDao(DistributeDao distributeDao) { this.distributeDao = distributeDao; } public List<File> getFile() { return file; } public void setFile(List<File> file) { this.file = file; } public List<String> getFileFileName() { return fileFileName; } public void setFileFileName(List<String> fileFileName) { this.fileFileName = fileFileName; } public List<String> getFileContentType() { return fileContentType; } public void setFileContentType(List<String> fileContentType) { this.fileContentType = fileContentType; } private void init() throws UnsupportedEncodingException{ ServletActionContext.getRequest().setCharacterEncoding("UTF-8"); ServletContext context = ServletActionContext.getServletContext(); } public String fileUpload() throws Exception{ init(); // 取得需要上传的文件数组 List<File> files = getFile(); if (files != null && files.size() > 0) { for (int i = 0; i < files.size(); i++) { FileOutputStream fos = new FileOutputStream(getSavePath() +
"\\" + getFileFileName().get(i)); FileInputStream fis = new FileInputStream(files.get(i)); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fis.close(); fos.close(); } TaskAppend taskAppend = distributeDao.findLeaderMsg(Integer.parseInt(taskid)); taskAppend.setTaskAllocationDoc(getFileFileName().get(0)); distributeDao.updateTaskAppend(taskAppend); } return "fileUpload"; } public String getTaskid() { return taskid; } public void setTaskid(String taskid) { this.taskid = taskid; } }
本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/4698467.html,如需转载请自行联系原作者