java中的上传下载----ajaxFileUpload+struts2

文件上传在项目中应该是非常常见的,而且很多时候,上传文件都只是一个小页面中的一个功能,要求在实现文件上传的前提下不刷新页面。而一般情况下将客户端的文件包装成网络地址传递到服务器端然后通过流来进行文件传输的任务都是使用浏览器来帮我们完成的,一般情况下,我们的form表单提交,我们自己可以手动拿到表单的值,然后封装起来,发送ajax请求,为了安全着想,js是不允许访问客户端的文件系统的,所以而文件传输需要浏览器来完成,ajax上传其实是在页面中一小块区域加一个iframe对象然后引用到另一个页面,提交引用的那个页面。

1、ajaxFileUpload文件下载地址 http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ 

2、

jsp页面 (<input type="file"/>默认的样式很丑,调整样式有点小麻烦)

我没有加表单,ajax提交表单应该没什么问题,方法很多网上百度

复制代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <title>My JSP 'index.jsp' starting page</title>

    <script type="text/javascript" src="js/jquery.js"></script>

        <script type="text/javascript" src="js/ajaxfileupload.js"></script>

        <script type="text/javascript">

    function ajaxFileUpload()

    {

        

        $("#loading")

        .ajaxStart(function(){

            $(this).show();

        })//开始上传文件时显示一个图片

        .ajaxComplete(function(){

            $(this).hide();

        });//文件上传完成将图片隐藏起来

        

        $.ajaxFileUpload

        (

            {

                url:'fileAction.action',//用于文件上传的服务器端请求地址

                secureuri:false,//一般设置为false

                fileElementId:'file',//文件上传空间的id属性  <input type="file" id="file" name="file" />

                dataType: 'json',//返回值类型 一般设置为json

                success: function (data, status)  //服务器成功响应处理函数

                {

                    //从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量

                    alert(data.message);

                },

                error: function (data, status, e)//服务器响应失败处理函数

                {

                    alert(e);

                }

            }

        )

    }

    

    function f_DL(){

        location.href="fileAction!download.action?filePath="+"D:\\apache-tomcat-7.0.41\\webapps\\ajaxFileUploadDemo\\upload\\1P5521N4-3.jpg";

    }

    </script>

    </head>

    <body>

        <img src="loading.gif" id="loading" style="display: none;">

        <input type="file" id="file" name="file" />

        <br />

        <input type="button" value="上传" onclick="ajaxFileUpload();">

        

        <input type="button" value="下载" onclick="f_DL()"/>

    </body>

</html>
复制代码


3、action

复制代码
package com.demo.action;



import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;



import javax.servlet.http.HttpServletResponse;



import org.apache.struts2.ServletActionContext;



import com.opensymphony.xwork2.ActionSupport;



@SuppressWarnings("serial")

public class FileAction extends ActionSupport {



    private File file;

    private String fileFileName;

    private String fileFileContentType;

    private String message = "0"; // 0格式错误 1成功(文件路径)  2失败

    private String filePath;



    public String getFilePath() {

        return filePath;

    }



    public void setFilePath(String filePath) {

        this.filePath = filePath;

    }



    public String getMessage() {

        return message;

    }



    public void setMessage(String message) {

        this.message = message;

    }



    public File getFile() {

        return file;

    }



    public void setFile(File file) {

        this.file = file;

    }



    public String getFileFileName() {

        return fileFileName;

    }



    public void setFileFileName(String fileFileName) {

        this.fileFileName = fileFileName;

    }



    public String getFileFileContentType() {

        return fileFileContentType;

    }



    public void setFileFileContentType(String fileFileContentType) {

        this.fileFileContentType = fileFileContentType;

    }



    @SuppressWarnings("deprecation")

    @Override

    public String execute() throws Exception {



        String path = ServletActionContext.getRequest().getRealPath("/upload");

        File file = new File(path); // 判断文件夹是否存在,如果不存在则创建文件夹

        if (!file.exists()) {

            file.mkdir();

        }

        String[] fileSuffix = new String[] { ".exe" };// 禁止文件

        try {

            File f = this.getFile();

            // 判断文件格式

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

                if (fileFileName.endsWith(fileSuffix[i])) {

                    message = "0";

                    return ERROR;

                }

            }

            FileInputStream inputStream = new FileInputStream(f);

            FileOutputStream outputStream = new FileOutputStream(path + "\\"

                    + fileFileName);

            byte[] buf = new byte[1024];

            int length = 0;

            while ((length = inputStream.read(buf)) != -1) {

                outputStream.write(buf, 0, length);

            }

            inputStream.close();

            outputStream.flush();

            message = path + "\\" + this.getFileFileName();

        } catch (Exception e) {

            e.printStackTrace();

            message = "2";

        }

        return SUCCESS;

    }



    public String download() {

        String path = filePath;

        HttpServletResponse response = ServletActionContext.getResponse();

        try {

            // path是指欲下载的文件的路径。

            File file = new File(path);

            // 取得文件名。

            String filename = file.getName();

            // 取得文件的后缀名。

            String ext = filename.substring(filename.lastIndexOf(".") + 1)

                    .toUpperCase();



            // 以流的形式下载文件。

            InputStream fis = new BufferedInputStream(new FileInputStream(path));

            byte[] buffer = new byte[fis.available()];

            fis.read(buffer);

            fis.close();

            // 清空response

            response.reset();

            // 设置response的Header

            String filenameString = new String(filename.getBytes("gbk"),

                    "iso-8859-1");

            response.addHeader("Content-Disposition", "attachment;filename="

                    + filenameString);

            response.addHeader("Content-Length", "" + file.length());

            OutputStream toClient = new BufferedOutputStream(response

                    .getOutputStream());

            response.setContentType("application/octet-stream");

            toClient.write(buffer);

            toClient.flush();

            toClient.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }

        return null;

    }



}
复制代码

4、struts2配置

复制代码
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

    <package name="struts2" namespace="/" extends="json-default">

        <action name="fileAction" class="com.demo.action.FileAction">

            <result type="json" name="success">

                <param name="contentType">

                    text/html

                </param>

            </result>

            <result type="json" name="error">

                <param name="contentType">

                    text/html

                </param>

            </result>

        </action>

    </package>

</struts>    
复制代码

 

为生活,一路向前

你可能感兴趣的:(ajaxFileUpload)