文件上传下载 anjuarjs1.x

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/V_Junk/article/details/82413688

文件上传下载 anjuarjs1.x

现在前面: 文章是 demo 级的实现功能而已,高手绕路

不多说,直接看代码:

  • FileServlet.java

/**
 * Servlet implementation class FileServlet
 */
@WebServlet(name = "fileServlet", urlPatterns = {"/fileServlet"})
public class FileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            //文件名称
            String fileName = request.getParameter("fileName");
            //存放路径 
            String prefix = "";
            String fullName = prefix + fileName;
            response.setContentType("application/force-download");//应用程序强制下载
            in = new FileInputStream(fullName);
            //设置响应头,对文件进行url编码
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            //设置文件大小 java.io.FileInputStream.available() 方法 返回 可读取的字节数的估计值
            response.setContentLength(in.available());
            out = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } finally {
            if (out ! = null){
                out.close();
            }
            if(in != null){
                in.close();
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doOption(request, response, "2");
    }

    /**
     * @param request
     * @param response
     * @param type     类型,1:下载,2:上传
     * @Title: doOption
     * @Description: Servlet 响应函数
     */
    private void doOption(HttpServletRequest request, HttpServletResponse response, String type) {
        String fileName;

        try {
            if ("2".equals(type)) {

                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                if (isMultipart) {

                    // 创建工厂(这里用的是工厂模式)
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    ServletContext servletContext = this.getServletConfig().getServletContext();
                    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
                    factory.setRepository(repository);
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(request);
                    InputStream ins = null;
                    FileOutputStream fos = null;
                    FileInputStream fis = null;
                    String filePath;
                    try {
                        for (FileItem item : items) {

                            if (!item.isFormField()) {
                                fileName = item.getName();
                                filePath = getServletContext().getRealPath("/") + fileName;
                                // 创建文件输出流
                                File file = new File(filePath);
                                if (!file.exists()) {
                                    try {
                                        file.createNewFile();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                fos = new FileOutputStream(file);
                                // 创建输入流
                                ins = item.getInputStream();
                                // 从输入流获取字节数组
                                byte b[] = new byte[1];
                                // 读取一个输入流的字节到b[0]中
                                int read = ins.read(b);
                                while (read != -1) {
                                    fos.write(b, 0, 1);
                                    read = ins.read(b);
                                }
                            } else {
                               // 处理其他参数
                            }
                        }

                    } finally {
                        if (fis != null) {
                            fis.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                        if (ins != null) {
                            ins.close();
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static class Encodes {

        private static final String DEFAULT_URL_ENCODING = "UTF-8";

        public static String urlEncode(String part) {
            try {
                return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }

    }

}

  • index.html
<html ng-app="myApp">

<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/chapter25.js"></script>
</head>
<div ng-controller="transFileController as s">
    <div style="float: left">
        <script>
            function fileChange() {
                var ele = document.getElementById('arpBtn');
                ele.click();
            }
        </script>
        <button onclick="fileUpload.click()">上传文件</button>
        <button ng-click="uploadFile()" style="display:none" id="arpBtn"></button>
        <input type="file" style="display:none" id="fileUpload" value="选择文件" onchange="fileChange()"/>
    </div>
    <div>
        <button ng-click="fileDownload()"> 文件下载</button>
    </div>
</div>

</html>
  • chapter25.js
var app = angular.module('myApp', []);

app.controller('transFileController', function ($scope, $http) {
    /**
     * @desc 换届凭证上传
     */
    $scope.uploadFile = function () {
        var formData = new FormData();
        var file = document.getElementById("fileUpload").files[0];

        formData.append('file', file);

        if (!file) {
            return;
        }
        $http({
            method: 'POST',
            url: 'fileServlet',
            data: formData,
            headers: {
                'Content-Type': undefined
            },
            transformRequest: angular.identity
        }).then(function (data) {
            console.log(data)
        }).catch(function (data) {
            console.log(data);
        })
    }

    $scope.fileDownload = function () {

        jQuery('<form action="fileServlet" method="get">' +  // action请求路径及推送方法
            '<input type="text" name="fileName" value="invokeWithinTransaction.JPG"/>' + // 文件名称及文件路径
            '</form>')
            .appendTo('body').submit().remove();
    }
})

其实 fileDownload 方法开始的时候是这样写的:

  $scope.fileDownload = function () {
        var param = {};
        param['fileName'] = 'invokeWithinTransaction.JPG';
        $http({
            method: 'GET',
            url: 'fileServlet',
            params: param
        }).then(function (data) {
            console.log(data);
        }).catch(function (data) {
            console.log(data);
        })
    }

这样的问题是数据会在 data 里面但是我不知道怎么保存成对应的文件。

至此。

猜你喜欢

转载自blog.csdn.net/V_Junk/article/details/82413688