dwr文件上传

前端之家收集整理的这篇文章主要介绍了dwr文件上传前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

配置FileService映射:

dwr.xml

  1. <create creator="new">
  2. <param name="class" value="com.demo.service.FileService"/>
  3. </create>


FileService:
  1. package com.demo.service;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6.  
  7. import org.apache.commons.io.FileUtils;
  8. import org.apache.commons.io.FilenameUtils;
  9. import org.directwebremoting.WebContext;
  10. import org.directwebremoting.WebContextFactory;
  11.  
  12. public class FileService {
  13. public String upload(InputStream inputStream,String fileName) throws IOException{
  14. String tempFileName=FilenameUtils.getName(fileName);
  15. String path=getRealPath("upload");
  16. File file=new File(path+File.separator+tempFileName);
  17. FileUtils.copyInputStreamToFile(inputStream,file);
  18. return file.getPath();
  19. }
  20. public String getRealPath(String dir){
  21. WebContext context=WebContextFactory.get();
  22. return context.getSession().getServletContext().getRealPath(dir);
  23. }
  24. }


upload.jsp:
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>文件上传</title>
  8. <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
  9. <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/util.js"></script>
  10. <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/FileService.js"></script>
  11. <script type="text/javascript">
  12. function upload(){
  13. var file=dwr.util.getValue("file");
  14. FileService.upload(file,file.value,function(result){
  15. alert(result);
  16. });
  17. }
  18. </script>
  19. </head>
  20. <body>
  21. 附件:<input type="file" id="file" name="file"><br/>
  22. <button onclick="upload();">上传</button>
  23. </body>
  24. </html>


结果:

附件已上传到upload文件夹中

猜你在找的Ajax相关文章