javaWeb上传与下载文件

简介

fileupload常用于web文件的上传,因为操作简单效率高,因而比较流行.

添加Maven依赖

<!--fileupload的Maven依赖-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

<!--处理流时用,fileUpload用-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

fileupload方法

javaWeb上传与下载文件

 javaWeb上传与下载文件

 

示例

文件的下载

package xin.student.fileoperator;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet("/download")
public class Download extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要下载的文件名
        String downloadFileName = "头像.jpg";
        //读取要下载的文件内容
        ServletContext servletContext = getServletContext();

        String mimeType = servletContext.getMimeType(downloadFileName);
        System.out.println("下载的文件类型:" + mimeType);
        //在回传前,通过响应头告诉客户端返回的数据类型
        resp.setContentType(mimeType);

        //获取浏览器不能用utf-8,要用base64
        //还要告诉客户端收到的数据是用于下载使用的(还是使用响应头),URLEncoder.encode()把汉字按指定的格式转为%xx的形式
        resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(downloadFileName, "UTF-8"));

        //获取资源的输入流,服务器解析的地址为http://ip/ 映射到web目录
        InputStream resourceAsStream = servletContext.getResourceAsStream("/" + downloadFileName);

        //获取相应的输出流
        OutputStream outputStream = resp.getOutputStream();

        //读取输入流中全部的数据,复制给给输入流,把下载的内容回传给客户端
        IOUtils.copy(resourceAsStream, outputStream);
    }
}

文件的上传

package xin.student.fileoperator;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.*;
import java.util.List;
import javax.servlet.ServletInputStream;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //判断是不是多段的数据(只有多段的数据,才是上传文件的)
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();

            //创建用于解析上传数据的工具类ServletFileUpLoad类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据,得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);

                for (FileItem fileItem : list) {
                    //普通表单项目
                    if (fileItem.isFormField()) {
                        //获取表单的name属性值
                        System.out.println("表单项的name属性值:" + fileItem.getFieldName());

                        //参数是字符集,防止乱码
                        System.out.println("表单项的value属性值:" + fileItem.getString("UTF-8"));
                    } else {//上传的是文件

                        System.out.println("表单项的name属性值:" + fileItem.getFieldName());
                        System.out.println("上传的文件名:" + fileItem.getName());

                        fileItem.write(new File("C:\\Users\\Administrator\\Desktop\\文件上传与下载\\"+fileItem.getName()));
                    }
                }

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

    public void destroy() {
    }
}

HTML文件

<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>File</title>
</head>
<body>
    <form action="/uploadServlet" method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="username"/> <br/>
        头像:<input type="file" name="photo"> <br/>
        <input type="submit" value="上传">
    </form>
    <a href="/download">下载</a>
</body>
</html>

上一篇:Unity5中新的Shader体系简析


下一篇:Unraid 2 安装 APPS 及官方汉化