java方法中的参数必须是BufferedImage,InputStream,FileTransfer三种中其中一个,
一般推荐使用FileTransfer,可以获取文件名、文件大小、和内置的inputStream。
后台实现文件上传方法
- public String fileUploadForDwr(ArrayList<FileTransfer> fileTransfer) {
- String tmp = "error";
- String fileName = ""; // 文件名
- String newFileName = ""; // 新文件名
- InputStream streamIn = null;
- OutputStream streamOut = null;
- long size = 1024 * 1024 * 5;
- if(fileTransfer.size() > size){
- return "文件不得大于5M";
- }
- WebContext webContext = WebContextFactory.get();
- String saveurl = webContext.getHttpServletRequest().getSession()
- .getServletContext().getRealPath("/upload");
- for (FileTransfer obj : fileTransfer) {
- if (obj.getFilename() != null && !obj.getFilename().equals("")) {
- fileName = obj.getFilename();
- if (fileName.lastIndexOf("\\") > -1) {
- fileName = fileName
- .substring(fileName.lastIndexOf("\\") + 1);
- }
- System.out.println(fileName);
- newFileName = CTools.createID()
- + fileName.substring(fileName.indexOf("."));
- try {
- streamIn = obj.getInputStream();
- streamOut = new FileOutputStream(new File(saveurl,
- newFileName));
- int bytesRead = 0;
- byte[] buffer = new byte[81920];
- while ((bytesRead = streamIn.read(buffer, 0, 81920)) != -1) {
- streamOut.write(buffer, 0, bytesRead);
- }
- streamOut.close();
- streamIn.close();
- tmp="success";
- } catch (FileNotFoundException ex) {
- } catch (IOException e) {
- // TODO: handle exception
- } finally {
- streamIn = null;
- streamOut = null;
- }
- }
- }
- return tmp;
- }
前台调用页面:
- <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>dwr3 文件上传</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript" src="/dwr/engine.js"></script>
- <script type="text/javascript" src="/dwr/util.js"></script>
- <script type="text/javascript" src="/dwr/interface/dwrFileUtil.js"></script>
- <script type="text/javascript">
- function uploadFile(){
- var file=dwr.util.getValue("attach");
- var str="123"
- var fileArr = new Array();//注意这里是用的集合,无论一个附件还是多个附件都可以了
- fileArr[0] = file;
- dwrFileUtil.fileUploadForDwr(fileArr,{callback:function (data){back(str,data)}});
- }
- function back(tmp,data){
- alert(3);
- alert(tmp+""+data);
- }
- </script>
- </head>
- <body>
- <input type="file" name="attach">
- <br />
- <input type="button" name="btnSub" onclick="uploadFile()" value="文件上传">
- </body>
- </html>
转载于:https://blog.51cto.com/tyyler/730599