Java文件上传

文件上传

原生的方式来完成

前端页面代码(jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
    <!-- multipart/form-data -->
    <form action="${pageContext.request.contextPath }/upload" enctype="multipart/form-data" method="post">
        <hr>
        用户名: <input type="text" name="username"><hr>
            头像: <input type="file" name="headimage"><hr>
            <input type="submit" value="提交"><hr>
    </form>
</body>
</html>

后端Servlet代码

package com.xiaoshitou.web.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件上传
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream in = request.getInputStream();
        int len = 0;
        byte[] bytes = new byte[1024*2];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = in.read(bytes)) != -1){
            out.write(bytes, 0, len);
        }
        // 这里直接把 输入的流里面的东西都打印出来了,也可以对输入流中的内容解析,然后持久化到磁盘中
        System.out.print(new String(out.toByteArray(),"utf-8"));

        out.close();
        in.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}

上传成功,控制带打印的结果

------WebKitFormBoundaryC6ADDE8SNt0FPina
Content-Disposition: form-data; name="username"

老黑
------WebKitFormBoundaryC6ADDE8SNt0FPina
Content-Disposition: form-data; name="headimage"; filename="个人文档.txt"
Content-Type: text/plain

windos 查看端口被那个进程占用     netstat -ano | findstr "8080"
windos    查看进程号的程序名字    tasklist|findstr "2720"


书写一个功能的时候,多问自己:
1 有没有线程安全问题
2 有没有性能问题
3 当前解决方案,有没有极端特殊情况
4 当前解决方案,理论上没有问题,实际操作,是否可行(数据库可行,java代码可行,前端页面可行)



------WebKitFormBoundaryC6ADDE8SNt0FPina--

使用fileupload来完成

服务端的servlet代码

// 使用fileupload来完成上传
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        try {
            // 解析请求
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem item : fileItems) {
                // 判断是否是form表单中的普通字段
                if (item.isFormField()){
                    // 获取提交的name值
                    String fieldName = item.getFieldName();
                    // 获取提交的value
                    String value = item.getString("utf-8");
                    System.out.println(fieldName);
                    System.out.println(value);
                }else{
                    // 是文件上传的字段
                    String fieldName = item.getFieldName(); // 提交的input的name值
                    String name = item.getName();// 上传文件的 文件名
                    // 存放在服务器的具体路径和文件名
                    String dir = this.getServletContext().getRealPath("/upload") + DirUtils.getDir(name);
                    File dirFile = new File(dir);
                    if (!dirFile.exists()){
                        dirFile.mkdirs();
                    }
                    // 将上传的文件写入file中
                    try {
                        item.write(new File(dirFile, UUIDUtils.getUUID()+name));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }

中间使用了两个工具类:DirUtil和UUIDUtils

package com.xiaoshitou.utils;
/**
* 根据文件名目录打散工具类
*/
public class DirUtils {
    public static String getDir(String name) {
        if (name != null) {
            int code = name.hashCode();
            return "/" + (code & 15) + "/" + (code >>> 4 & 15);
        }
        return null;
    }

}
package com.xiaoshitou.utils;

import java.util.UUID;
/**
* 防止文件名重复UUID重写文件名的方法
*/
public class UUIDUtils {
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
原文地址:https://www.cnblogs.com/xiaoshitoutest/p/7358802.html