dwr的ajax上传

	<!-- 上传 -->
		<create creator="new" javascript="fileUpload">
			<param name="class" value="upload.FileUpload" />
		</create>

 lib依赖

commons-fileupload-1.2.jar

commons-io-1.3.1.jar

 dwr.jar

package upload;

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);
		if (!file.exists()) {
			file.mkdirs();
		}
		int available = uploadFile.available();// 上传inputStream流的大小
		byte[] b = new byte[available];// 转化为字节
		String newname = filename.substring(filename.lastIndexOf("\\") + 1);// 获得原始文件名
		FileOutputStream foutput = new FileOutputStream(file + "/" + newname);// 输出流至完整目地
		uploadFile.read(b);// 读流
		foutput.write(b);// 写流
		foutput.flush();
		foutput.close();
		uploadFile.close();
		return realtivepath + newname;
	}

	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;
	}

	// 设置限制格式以,分开
	public void setAllowedFilesList(String allowedFilesList) {

		String[] tmp = allowedFilesList.split(",");// 用,打散分成数组并保存.
		int size = tmp.length;
		temp = new String[size];
		for (int i = 0; i < size; i++) {
			temp[i] = tmp[i];
			System.out.println("限制的类型为:" + temp[i]);
		}

	}

	private String[] temp;// 临时存放所设置的扩展名

	// 判断当前类型否符合setAllowedFilesList所限定的类型需要用到setAllowedFilesList生成的数组变量temp
	private boolean checkExt(String ext) {
		boolean bool = false;

		for (int i = 0; i < temp.length; i++) {

			if (ext.equals("." + temp[i])) {

				bool = true;
			}
		}
		return bool;
	}

	// 限制 文件上传大小的函数
	private boolean limitsize(File aa, long n) {

		boolean bool = true;
		long i = aa.length() / 1048576;
		System.out.println("文件字节大小 是:" + i);
		if (i > n) {
			System.out.print("上传文件过大!");
			bool = false;
		}
		return bool;
	}

	/**
	 * 删除单个文件
	 * 
	 * @param fileName
	 *            要删除的文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				System.out.println("删除单个文件" + fileName + "成功!");
				return true;
			} else {
				System.out.println("删除单个文件" + fileName + "失败!");
				return false;
			}
		} else {
			System.out.println("删除单个文件失败:" + fileName + "不存在!");
			return false;
		}
	}
}

 

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>fileupload</title>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<script type='text/javascript' src="<%=path%>/dwr/interface/fileUpload.js"></script>
<script type='text/javascript' src="<%=path%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=path%>/dwr/interface/xiaoyi.js"></script>
<script type='text/javascript' src="<%=path%>/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];   
    alert('dddddddddddddddd');
    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" οnclick="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" οnclick="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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值