ajax框架怎么学,Ajax框架之DWR学习(文件上传案例)

  • Post author:
  • Post category:其他


DWR文件上传起来 还是挺方便的,直接就是咔咔的上传 ,实现了静态的文件上传,老爽了,需要依赖commons-fileupload 这个上传包。

20586_0.png

目录结构

20586_1.png

环境搭建

pom.xml

commons-fileupload 这个是文件上传所需要的依赖包

xsi:schemaLocation=”https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd”>

4.0.0

yellowcong

day11_29

war

0.0.1-SNAPSHOT

day11_29 Maven Webapp

https://maven.apache.org

junit

junit

4.10

test

org.directwebremoting

dwr

3.0.2-RELEASE

commons-logging

commons-logging

1.0.4

commons-fileupload

commons-fileupload

1.3.1

day11_29

web.xml

xmlns=”https://java.sun.com/xml/ns/javaee”

xsi:schemaLocation=”https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”

id=”WebApp_ID” version=”2.5″>

day1_27_dwr

org.directwebremoting.servlet.DwrListener

dwr-invoker

org.directwebremoting.servlet.DwrServlet

debug

true

1

dwr-invoker

/dwr/*

index.jsp

dwr.xml配置

上传服务

package com.yellowcong.service;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import org.apache.commons.io.FileUtils;

import org.directwebremoting.WebContext;

import org.directwebremoting.WebContextFactory;

public class UploadService {

/**

* 这个导入的是InputStream 的方法,而不是通过 File

*

* @param in

* 输入流

* @param filename

* 文件名称

* @return

* @throws IOException

*/

public String upload(InputStream in, String filename) throws IOException {

// 对于 服务器,我们需要通过ServletContext 获取我们的绝对路径 ,存储在可操作的文件夹中

//这个对象是DWR给我们封装的

WebContext context = WebContextFactory.get();

//获取文件路径

String path =context.getServletContext().getRealPath(“/resources/”);

//新建文件

File outFile = new File(path+File.separator+filename);

System.out.println(outFile.getAbsolutePath());

//当文件夹不存在的情况新建

if(!outFile.getParentFile().exists()){

outFile.getParentFile().mkdirs();

}

//写文件

FileUtils.copyInputStreamToFile(in, outFile);

return outFile.getAbsolutePath();

}

}

界面

index.jsp

pageEncoding=”UTF-8″%>

function uploadFile(){

var file = document.getElementById(“file_upload”);

var names = file.value.split(“\”);

var fileName = names[names.length-1];

UploadService.upload(file,fileName,function(data){

alert(“文件路径t”+data);

});

}

文件上传

运行结果

20586_2.png

上传文件

20586_3.png