ajax jsp 无刷新上传文件

首先要说的就是 ajax 是无法实现上传文件的,可以想一下ajax与后台通信都是通过传递字符串,怎么能传递文件呢?其实出于安全考虑js是不能操作文件的,所以就不要再说用ajax来实现文件的上传了,这是不可能的。
    而本文实现的文件上传也是无页面刷新的,可以说是一种"类似AJAX"方法。
    开始之前先说两句无关的,其实在ajax出现之前,web应用也可以是无刷新的,那时大多通过IFrame来做到这一点。当然Ajax出现之后,人们一窝蜂地投奔Ajax 的阵营了,iFrame 就乏人问津了。但是用iFrame来实现无刷新上传文件确实一个很好的选择。ps:Ajax技术基本上可以说是由google公司带起来的,但少Gmail中上传文件用的还是 IFrame,所以说使用IFrame来上传文件是最好的选择。
    我在这里这里用的技术是jsp,其实asp,php等也是一样可以这么实现的
    一共两个文件就可实现:index.html 和 upload.jsp,在这里讲解一下,文后会附上源码

--index.html

html 代码
  1. <html>   
  2. <body>   
  3.   
  4. <form action="upload.jsp" id="form1" name="form1" encType="multipart/form-data"  method="post" target="hidden_frame" >   
  5.     <input type="file" id="file" name="file" style="width:450">   
  6.     <INPUT type="submit" value="上传文件"><span id="msg"></span>   
  7.     <br>   
  8.     <font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上传</font>                 
  9.     <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>   
  10. </form>   
  11.   
  12. </body>   
  13. </html>   
  14.   
  15. <script type="text/javascript">   
  16. function callback(msg)   
  17. {   
  18.     document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;   
  19.     document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";   
  20. }   
  21. </script>  


 index.html 中主要要做的就是写一个 form 和 iframe ,并把 form 的 target 设为 iframe 的名字,注意要把 iframe 设为不可见,其他的都是正常的文件上传的写法,这样刷新的页面就是这个隐藏的 Iframe ,而在 index.html 中是不会有页面刷新的,js的 callback 方法是回调方法。用于清空文件上传框和显示后台信息,注意清空文件上传框的方法,和普通方法有点不一样。

--upload.jsp

jsp 代码
  1. <%@ page language="java" contentType="text/html; charset=gb2312" %>   
  2. <%@ page import="com.jspsmart.upload.SmartUpload"%>   
  3.   
  4. <%   
  5.     //新建一个SmartUpload对象   
  6.     SmartUpload su = new SmartUpload();   
  7.   
  8.     //上传初始化   
  9.     su.initialize(pageContext);   
  10.   
  11.     // 设定上传限制   
  12.     //1.限制每个上传文件的最大长度。   
  13.     su.setMaxFileSize(10000000);   
  14.   
  15.     //2.限制总上传数据的长度。   
  16.     su.setTotalMaxFileSize(20000000);   
  17.   
  18.     //3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。   
  19.     su.setAllowedFilesList("doc,txt,jpg,rar,mid,waw,mp3,gif");   
  20.        
  21.     boolean sign = true;   
  22.        
  23.     //4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。   
  24.     try {   
  25.         su.setDeniedFilesList("exe,bat,jsp,htm,html");   
  26.   
  27.         //上传文件   
  28.         su.upload();   
  29.         //将上传文件保存到指定目录   
  30.         su.save("c:\\");  
  31.  
  32.     } catch (Exception e) {  
  33.         e.printStackTrace();  
  34.         sign = false;  
  35.     }  
  36.     if(sign==true)  
  37.     {  
  38.         out.println("<script>parent.callback('upload file success')</script>");  
  39.     }else  
  40.     {  
  41.         out.println("<script>parent.callback('upload file error')</script>");   
  42.     }   
  43. %>   




upload.jsp 中只要注意最后输出的格式就可以了。其实原理就是输出一段js代码到 iframe 中,然后在iframe中来控制它的父页面。

    OK,至此一个无刷新的页面上传组件就做好了,
不要忘了在 WEB-INF/lib 下加上必须的 jspSmartUpload.jar 包
    需要说明的是使用Iframe来上传,状态栏还是会有刷新的,因为iframe 中的页面刷新了嘛,但是外部页面,就是你所看到的页面是没有刷新的,所以也可以说是类似Ajax上传。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java SSM 框架可以通过使用 Hadoop 的 Java API 直接操作 HDFS 文件系统,以下是展示 HDFS 文件列表、上传文件、删除文件、下载文件的前后端代码示例。 前端代码: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HDFS文件操作</title> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript"> $(document).ready(function () { $("#listFileBtn").click(function () { $.ajax({ url: "/hdfs/list", type: "GET", dataType: "json", success: function (data) { $("#fileTable tbody").empty(); for (var i = 0; i < data.length; i++) { $("#fileTable tbody").append("<tr><td>" + data[i] + "</td><td><button class='btn btn-danger' onclick='deleteFile(\"" + data[i] + "\")'>删除</button></td><td><button class='btn btn-primary' onclick='downloadFile(\"" + data[i] + "\")'>下载</button></td></tr>") } } }) }); $("#uploadFileBtn").click(function () { var formData = new FormData(); formData.append("file", $("#file")[0].files[0]); $.ajax({ url: "/hdfs/upload", type: "POST", data: formData, processData: false, contentType: false, success: function (data) { alert(data); $("#listFileBtn").click(); } }) }); }); function deleteFile(fileName) { $.ajax({ url: "/hdfs/delete?fileName=" + fileName, type: "GET", dataType: "text", success: function (data) { alert(data); $("#listFileBtn").click(); } }) } function downloadFile(fileName) { window.open("/hdfs/download?fileName=" + fileName); } </script> </head> <body> <div class="container"> <h1>HDFS文件操作</h1> <hr> <div class="row"> <div class="col-md-4"> <h4>上传文件</h4> <br> <div class="form-group"> <input type="file" id="file" name="file"> </div> <button class="btn btn-success" id="uploadFileBtn">上传</button> </div> <div class="col-md-4"> <h4>文件列表</h4> <br> <button class="btn btn-primary" id="listFileBtn">刷新</button> <br><br> <table class="table" id="fileTable"> <thead> <tr> <th>文件名</th> <th>删除</th> <th>下载</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </div> </body> </html> ``` 后端代码: ``` @Controller @RequestMapping("/hdfs") public class HdfsController { private final static String HDFS_PATH = "hdfs://localhost:9000"; private final FileSystem fileSystem; public HdfsController() throws IOException { Configuration configuration = new Configuration(); configuration.set("fs.defaultFS", HDFS_PATH); fileSystem = FileSystem.get(configuration); } @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public List<String> listFile() throws IOException { RemoteIterator<LocatedFileStatus> fileIterator = fileSystem.listFiles(new Path("/"), true); List<String> fileList = new ArrayList<>(); while (fileIterator.hasNext()) { LocatedFileStatus fileStatus = fileIterator.next(); fileList.add(fileStatus.getPath().toString()); } return fileList; } @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { if (file.isEmpty()) { return "上传文件为空"; } String fileName = file.getOriginalFilename(); Path path = new Path("/" + fileName); if (fileSystem.exists(path)) { return "文件已存在"; } FSDataOutputStream outputStream = fileSystem.create(path); outputStream.write(file.getBytes()); outputStream.close(); return "上传成功"; } @RequestMapping(value = "/delete", method = RequestMethod.GET) @ResponseBody public String deleteFile(@RequestParam("fileName") String fileName) throws IOException { Path path = new Path("/" + fileName); if (!fileSystem.exists(path)) { return "文件不存在"; } fileSystem.delete(path, true); return "删除成功"; } @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) throws IOException { Path path = new Path("/" + fileName); if (!fileSystem.exists(path)) { return null; } FSDataInputStream inputStream = fileSystem.open(path); byte[] data = IOUtils.toByteArray(inputStream); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=" + fileName); HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(data, headers, status); return responseEntity; } } ``` 以上代码实现了展示 HDFS 文件列表、上传文件、删除文件、下载文件的功能。其中,前端使用了 Bootstrap 框架美化界面,后端使用了 Spring MVC 框架处理请求。 ### 回答2: JavaSSM框架是一种结合了Java语言、Spring框架、Spring MVC框架和MyBatis ORM框架的开发架构,用于构建基于Java的后端应用。要展示HDFS文件列表、上传文件、删除文件和下载文件,需要前后端代码配合实现。下面给出一个简单的示例代码。 后端代码: 1. 首先在Spring配置文件中配置HDFS相关的bean: ```xml <!-- HDFS配置 --> <property name="fs.defaultFS" value="hdfs://localhost:9000"/> <property name="fs.hdfs.impl" value="org.apache.hadoop.hdfs.DistributedFileSystem"/> <bean id="hdfsConfiguration" class="org.apache.hadoop.conf.Configuration" factory-method="create"/> <bean id="fileSystem" class="org.apache.hadoop.fs.FileSystem" factory-bean="hdfsConfiguration" factory-method="get"/> ``` 2. 创建Controller类,处理前端请求: ```java @Controller public class FileController { @Autowired private FileSystem fileSystem; // 文件列表展示 @RequestMapping("/list") public String listFiles(Model model) throws IOException { FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/")); // 获取根目录下的文件列表 model.addAttribute("files", Arrays.asList(fileStatuses)); return "fileList"; } // 文件上传 @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException { if (!multipartFile.isEmpty()) { String fileName = multipartFile.getOriginalFilename(); Path filePath = new Path("/" + fileName); // 在HDFS上创建一个文件并写入数据 FSDataOutputStream outputStream = fileSystem.create(filePath); outputStream.write(multipartFile.getBytes()); outputStream.close(); } return "redirect:/list"; } // 文件删除 @RequestMapping("/delete/{fileName}") public String deleteFile(@PathVariable("fileName") String fileName) throws IOException { Path filePath = new Path("/" + fileName); fileSystem.delete(filePath, false); // 删除文件 return "redirect:/list"; } // 文件下载 @RequestMapping("/download/{fileName}") public ResponseEntity<byte[]> downloadFile(@PathVariable("fileName") String fileName) throws IOException { Path filePath = new Path("/" + fileName); FSDataInputStream inputStream = fileSystem.open(filePath); byte[] fileBytes = IOUtils.toByteArray(inputStream); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=" + fileName); ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(fileBytes, headers, HttpStatus.OK); return responseEntity; } } ``` 前端代码: 1. 文件列表页面(fileList.jsp): ```html <!DOCTYPE html> <html> <head> <title>HDFS文件列表</title> </head> <body> <h1>HDFS文件列表</h1> <table> <tr> <th>文件名</th> <th>操作</th> </tr> <c:forEach items="${files}" var="file"> <tr> <td>${file.path.toString().substring(1)}</td> <td> <a href="/download/${file.path.toString().substring(1)}">下载</a> <a href="/delete/${file.path.toString().substring(1)}">删除</a> </td> </tr> </c:forEach> </table> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form> </body> </html> ``` 总结:以上就是使用JavaSSM框架展示HDFS文件列表、上传文件、删除文件和下载文件的前后端代码。通过前端页面和后端Controller的配合,可以实现对HDFS文件的基本操作。 ### 回答3: Java SSM(Spring+Spring MVC+MyBatis)是一种常用的Java Web开发框架。下面是一个展示HDFS文件列表、上传文件、删除文件、下载文件的前后端代码示例。 后端Java代码: 1. 文件列表请求接口: ```java @RestController @RequestMapping("/hdfs") public class HdfsController { @Autowired private HdfsService hdfsService; @RequestMapping("/filelist") public List<String> getFileList() { return hdfsService.getFileList(); } } ``` 2. 上传文件请求接口: ```java @RestController @RequestMapping("/hdfs") public class HdfsController { @Autowired private HdfsService hdfsService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile multipartFile) { return hdfsService.uploadFile(multipartFile); } } ``` 3. 删除文件请求接口: ```java @RestController @RequestMapping("/hdfs") public class HdfsController { @Autowired private HdfsService hdfsService; @DeleteMapping("/delete") public String deleteFile(@RequestParam("filename") String filename) { return hdfsService.deleteFile(filename); } } ``` 4. 下载文件请求接口: ```java @RestController @RequestMapping("/hdfs") public class HdfsController { @Autowired private HdfsService hdfsService; @GetMapping("/download") public void downloadFile(@RequestParam("filename") String filename, HttpServletResponse response) { hdfsService.downloadFile(filename, response); } } ``` 前端代码(使用JavaScript + jQuery): 1. 展示文件列表: ```javascript $.ajax({ url: "/hdfs/filelist", type: "GET", success: function(data) { // 处理返回的文件列表data for(var i=0; i<data.length; i++) { var filename = data[i]; // 在页面中展示文件名 $("#filelist").append("<li>" + filename + "</li>"); } } }); ``` 2. 上传文件: ```javascript $("#upload-form").submit(function(e) { e.preventDefault(); var formData = new FormData($(this)[0]); $.ajax({ url: "/hdfs/upload", type: "POST", data: formData, processData: false, contentType: false, success: function(data) { // 处理上传成功后的返回数据data console.log("上传成功"); } }); }); ``` 3. 删除文件: ```javascript function deleteFile(filename) { $.ajax({ url: "/hdfs/delete", type: "DELETE", data: { filename: filename }, success: function(data) { // 处理删除成功后的返回数据data console.log("删除成功"); } }); } ``` 4. 下载文件: ```javascript function downloadFile(filename) { window.location.href = "/hdfs/download?filename=" + filename; } ``` 以上便是一个简单的展示HDFS文件列表、上传文件、删除文件、下载文件的Java SSM框架的前后端代码示例。需要根据实际情况进行适当修改和完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值