首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

DWR 3.0 下传文件

2012-10-29 
DWR 3.0 上传文件DWR 3.0 上传文件关键字: dwr 3.0 无刷新 上传文件 upload file 第一步:需要文件包,其实

DWR 3.0 上传文件
DWR 3.0 上传文件
关键字: dwr 3.0 无刷新 上传文件 upload file
第一步:需要文件包,其实就是dwr 3.0中例子所需要的包, dwr.jar 、 commons-fileupload-1.2.jar 、 commons-io-1.3.1.jar 。







第二步:编辑web.xml,添加dwr-invoke

Xml代码
<servlet> 
    <display-name>DWR Sevlet</display-name> 
    <servlet-name>dwr-invoker</servlet-name> 
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> 
    <init-param> 
        <description>是否打开调试功能</description> 
        <param-name>debug</param-name> 
        <param-value>true</param-value> 
    </init-param> 
    <init-param> 
        <description>日志级别有效值为: FATAL, ERROR, WARN (the default), INFO and DEBUG.</description> 
        <param-name>logLevel</param-name> 
        <param-value>DEBUG</param-value> 
    </init-param> 
    <init-param> 
        <description>是否激活反向Ajax</description> 
        <param-name>activeReverseAjaxEnabled</param-name> 
        <param-value>true</param-value> 
    </init-param> 
    <init-param>    
         <description>在WEB启动时是否创建范围为application的creator</description>    
         <param-name>initApplicationScopeCreatorsAtStartup</param-name>    
         <param-value>true</param-value>    
    </init-param>    
    <init-param> 
        <description>在WEB启动时是否创建范围为application的creator</description>    
        <param-name>preferDataUrlSchema</param-name> 
        <param-value>false</param-value> 
    </init-param> 
        <load-on-startup>1</load-on-startup>    
      
</servlet> 
<servlet-mapping> 
    <servlet-name>dwr-invoker</servlet-name> 
    <url-pattern>/dwr/*</url-pattern> 
</servlet-mapping> 

<servlet>
<display-name>DWR Sevlet</display-name>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<description>是否打开调试功能</description>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<description>日志级别有效值为: FATAL, ERROR, WARN (the default), INFO and DEBUG.</description>
<param-name>logLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
<init-param>
<description>是否激活反向Ajax</description>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param> 
     <description>在WEB启动时是否创建范围为application的creator</description> 
     <param-name>initApplicationScopeCreatorsAtStartup</param-name> 
     <param-value>true</param-value> 
</init-param> 
<init-param>
<description>在WEB启动时是否创建范围为application的creator</description> 
   <param-name>preferDataUrlSchema</param-name>
    <param-value>false</param-value>
    </init-param>
<load-on-startup>1</load-on-startup> 

</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>


第三步:创建上传类FileUpload.java,编辑代码,内容如下:

Java代码
package learn.dwr.upload_download;  
 
import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics2D;  
import java.awt.geom.AffineTransform;  
import java.awt.image.AffineTransformOp;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import org.directwebremoting.WebContext;  
import org.directwebremoting.WebContextFactory;  
 
/** 
* title: 文件上传 
* @author Administrator 
* @时间 2009-11-22:上午11:40:22 
*/ 
public class FileUpload {  
 
    /** 
     * @param uploadImage 圖片文件流 
     * @param uploadFile 需要用简单的文本文件,如:.txt文件,不然上传会出乱码 
     * @param color 
     * @return 
     */ 
    public BufferedImage uploadFiles(BufferedImage uploadImage,  
            String uploadFile, String color) {  
        // uploadImage = scaleToSize(uploadImage);  
        // uploadImage =grafitiTextOnImage(uploadImage, uploadFile, color);  
        return uploadImage;  
    }  
 
    /** 
     * 文件上传时使用InputStream类进行接收,在DWR官方例中是使用String类接收简单内容 
     *  
     * @param uploadFile 
     * @return 
     */ 
    public String uploadFile(InputStream uploadFile, String filename)  
            throws Exception {  
        WebContext webContext = WebContextFactory.get();  
        String realtivepath = webContext.getContextPath() + "/upload/";  
        String saveurl = webContext.getHttpServletRequest().getSession()  
                .getServletContext().getRealPath("/upload");  
        File file = new File(saveurl + "/" + filename);  
        // if (!file.exists()) {  
        // file.mkdirs();  
        // }  
        int available = uploadFile.available();  
        byte[] b = new byte[available];  
        FileOutputStream foutput = new FileOutputStream(file);  
        uploadFile.read(b);  
        foutput.write(b);  
        foutput.flush();  
        foutput.close();  
        uploadFile.close();  
        return realtivepath + filename;  
    }  
 
    private BufferedImage scaleToSize(BufferedImage uploadImage) {  
        AffineTransform atx = new AffineTransform();  
        atx  
                .scale(200d / uploadImage.getWidth(), 200d / uploadImage  
                        .getHeight());  
        AffineTransformOp atfOp = new AffineTransformOp(atx,  
                AffineTransformOp.TYPE_BILINEAR);  
        uploadImage = atfOp.filter(uploadImage, null);  
        return uploadImage;  
    }  
 
    private BufferedImage grafitiTextOnImage(BufferedImage uploadImage,  
            String uploadFile, String color) {  
        if (uploadFile.length() < 200) {  
            uploadFile += uploadFile + " ";  
        }  
        Graphics2D g2d = uploadImage.createGraphics();  
        for (int row = 0; row < 10; row++) {  
            String output = "";  
            if (uploadFile.length() > (row + 1) * 20) {  
                output += uploadFile.substring(row * 20, (row + 1) * 20);  
            } else {  
                output = uploadFile.substring(row * 20);  
            }  
            g2d.setFont(new Font("SansSerif", Font.BOLD, 16));  
            g2d.setColor(Color.blue);  
            g2d.drawString(output, 5, (row + 1) * 20);  
        }  
        return uploadImage;  
    }  


package learn.dwr.upload_download;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

/**
* title: 文件上传
* @author Administrator
* @时间 2009-11-22:上午11:40:22
*/
public class FileUpload {

/**
* @param uploadImage 圖片文件流
* @param uploadFile 需要用简单的文本文件,如:.txt文件,不然上传会出乱码
* @param color
* @return
*/
public BufferedImage uploadFiles(BufferedImage uploadImage,
String uploadFile, String color) {
// uploadImage = scaleToSize(uploadImage);
// uploadImage =grafitiTextOnImage(uploadImage, uploadFile, color);
return uploadImage;
}

/**
* 文件上传时使用InputStream类进行接收,在DWR官方例中是使用String类接收简单内容
*
* @param uploadFile
* @return
*/
public String uploadFile(InputStream uploadFile, String filename)
throws Exception {
WebContext webContext = WebContextFactory.get();
String realtivepath = webContext.getContextPath() + "/upload/";
String saveurl = webContext.getHttpServletRequest().getSession()
.getServletContext().getRealPath("/upload");
File file = new File(saveurl + "/" + filename);
// if (!file.exists()) {
// file.mkdirs();
// }
int available = uploadFile.available();
byte[] b = new byte[available];
FileOutputStream foutput = new FileOutputStream(file);
uploadFile.read(b);
foutput.write(b);
foutput.flush();
foutput.close();
uploadFile.close();
return realtivepath + filename;
}

private BufferedImage scaleToSize(BufferedImage uploadImage) {
AffineTransform atx = new AffineTransform();
atx
.scale(200d / uploadImage.getWidth(), 200d / uploadImage
.getHeight());
AffineTransformOp atfOp = new AffineTransformOp(atx,
AffineTransformOp.TYPE_BILINEAR);
uploadImage = atfOp.filter(uploadImage, null);
return uploadImage;
}

private BufferedImage grafitiTextOnImage(BufferedImage uploadImage,
String uploadFile, String color) {
if (uploadFile.length() < 200) {
uploadFile += uploadFile + " ";
}
Graphics2D g2d = uploadImage.createGraphics();
for (int row = 0; row < 10; row++) {
String output = "";
if (uploadFile.length() > (row + 1) * 20) {
output += uploadFile.substring(row * 20, (row + 1) * 20);
} else {
output = uploadFile.substring(row * 20);
}
g2d.setFont(new Font("SansSerif", Font.BOLD, 16));
g2d.setColor(Color.blue);
g2d.drawString(output, 5, (row + 1) * 20);
}
return uploadImage;
}
}
第四步:添加到dwr.xml

Java代码
<create creator="new">  
    <param name="class" value="learn.dwr.upload_download.FileUpload" />  
</create> 

<create creator="new">
<param name="class" value="learn.dwr.upload_download.FileUpload" />
</create> 第五步:添加前台html代码

Html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>二进制文件处理,文件上传</title> 
<script type='text/javascript' src='/learnajax/dwr/interface/FileUpload.js'></script> 
<script type='text/javascript' src='/learnajax/dwr/engine.js'></script> 
<script type='text/javascript' src='/learnajax/dwr/util.js'></script> 
<script type='text/javascript' > 
function uploadFiles(){  
    var uploadImage = dwr.util.getValue("uploadImage");  
     FileUpload.uploadFiles(uploadImage, "", "", function(imageURL) {  
        alert(imageURL);  
        dwr.util.setValue('image', imageURL);  
  });  
 
}  
function uploadFile(){  
    var uploadFile = dwr.util.getValue("uploadFile");  
    //var uploadFile =document.getElementById("uploadFile").value;  
    var uploadFileuploadFile_temp = uploadFile.value.replace("\","/");  
    var filenames = uploadFile.value.split("/");  
    var filename = filenames[filenames.length-1];  
    //var eextension = e[e.length-1];  
    FileUpload.uploadFile(uploadFile,filename,function(data){  
        var file_a= document.getElementById("file_a");  
        file_a.href=data;  
        file_a.innerHTML=data;  
        document.getElementById("filediv").style.display="";  
    });  
}  
      
</script> 
</head> 
 
<body> 
<table border="1" cellpadding="3" width="50%"> 
    <tr> 
        <td>Image</td> 
        <td><input type="file" id="uploadImage" /></td> 
        <td><input type="button" onclick="uploadFiles()" value="upload"/><div id="image.container">&nbsp;</div></td> 
    </tr> 
    <tr> 
        <td>File</td> 
        <td><input type="file" id="uploadFile" /></td> 
        <td><input type="button" onclick="uploadFile()" value="upload"/><div id="file.container">&nbsp;</div></td> 
    </tr> 
    <tr> 
        <td colspan="3"></td> 
    </tr> 
</table> 
<img id="image" src="javascript:void(0);"/> 
<div id="filediv" style="display:none;"> 
<a href="" id="file_a">上传的文件</a> 
</div> 
</body> 
</html> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>二进制文件处理,文件上传</title>
<script type='text/javascript' src='/learnajax/dwr/interface/FileUpload.js'></script>
<script type='text/javascript' src='/learnajax/dwr/engine.js'></script>
<script type='text/javascript' src='/learnajax/dwr/util.js'></script>
<script type='text/javascript' >
function uploadFiles(){
var uploadImage = dwr.util.getValue("uploadImage");
FileUpload.uploadFiles(uploadImage, "", "", function(imageURL) {
alert(imageURL);
    dwr.util.setValue('image', imageURL);
  });

}
function uploadFile(){
var uploadFile = dwr.util.getValue("uploadFile");
//var uploadFile =document.getElementById("uploadFile").value;
var uploadFile_temp = uploadFile.value.replace("\","/");
var filenames = uploadFile.value.split("/");
var filename = filenames[filenames.length-1];
//var extension = e[e.length-1];
FileUpload.uploadFile(uploadFile,filename,function(data){
var file_a= document.getElementById("file_a");
file_a.href=data;
file_a.innerHTML=data;
document.getElementById("filediv").style.display="";
});
}

</script>
</head>

<body>
<table border="1" cellpadding="3" width="50%">
<tr>
    <td>Image</td>
        <td><input type="file" id="uploadImage" /></td>
        <td><input type="button" onclick="uploadFiles()" value="upload"/><div id="image.container">&nbsp;</div></td>
    </tr>
    <tr>
    <td>File</td>
        <td><input type="file" id="uploadFile" /></td>
        <td><input type="button" onclick="uploadFile()" value="upload"/><div id="file.container">&nbsp;</div></td>
    </tr>
    <tr>
    <td colspan="3"></td>
    </tr>
</table>
<img id="image" src="javascript:void(0);"/>
<div id="filediv" style="display:none;">
<a href="" id="file_a">上传的文件</a>
</div>
</body>
</html>
 
添加进度条么,就需要用reverse ajax 进行配合使用了。
1 楼 easonfans 2011-02-19   都是复制粘贴的,都不可用……
不负责! 2 楼 a446532385 2011-12-01   activeReverseAjaxEnabledeasonfans 写道都是复制粘贴的,都不可用……
不负责!
确实 ERROR错误

热点排行