Java Web 文件上传

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

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>Insert title here</title>
</head>
<body>

<h1>上传头像</h1>
<hr/>

<form action="CommonServlet" method = "post"  enctype = "multipart/form-data">

    姓名: <input type = "text"  name = "name" /> <br/>
    密码: <input type = "text"  name = "password" /> <br/>

    爱好: <input type = "checkbox"  name = "hobyStr"  value = "basketball"/>篮球
                <input type = "checkbox"  name = "hobyStr"  value = "football"/>足球
                <input type = "checkbox"  name = "hobyStr"  value = "iceball"/> 冰球 
                <br>

    头像: <input type = "file"  name = "headImg" /> <br>
    靓图: <input type = "file"  name = "zoneImg" /> <br>
    靓图: <input type = "file"  name = "zoneImg"/> <br>
    靓图: <input type = "file"  name = "zoneImg"/> <br>

    <input type = "submit"  value = "提交"/>

</form>


注意:

1.设置form表单的enctype属性值为:”multipart/form-data”;
2.input的type属性值为”file”;

servlet代码:

/**
 * 上传图片3,这里上传的图片分头像和空间图片。
 * @param req
 * @param servlet
 * @throws Exception 
 */
private static void uploadImg3(HttpServletRequest req, HttpServletResponse resp,CommonServlet servlet) throws Exception {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    //parse request
    List<FileItem>fileItems = servletFileUpload.parseRequest(req);

    //初始化map
    HashMap<String, Object> map = new HashMap<>();

    //初始化User
    User user = new User();

    //遍历
    for(FileItem item : fileItems){

        //非file文档
        if (item.isFormField()) {

            if (map.get(item.getFieldName())!=null) {
                String lastValue = (String)map.get(item.getFieldName());
                map.put(item.getFieldName(), lastValue+","+item.getString("utf-8"));
            }else{
                map.put(item.getFieldName(), item.getString("utf-8"));
            }
        }else{

            String filetype = item.getFieldName();

            if ("headImg".equals(filetype)) {

                String headF = servlet.getServletContext().getRealPath("\\head");
                //根据UUID区分
                UUID uuid =  UUID.randomUUID();
                //上传图片名
                String imgName = item.getName();
                //存储图片名
                String headUuidName = uuid+"_"+imgName;
                //头像URL
                String headUrl = "head"+File.separator+uuid+"_"+imgName;
                //设置头像url
                user.setHeadUrl(headUrl);
                //将图片存进文件
                File headFile = new File(headF);
                if (!headFile.exists()) {
                    headFile.mkdirs();
                }
                OutputStream output = new FileOutputStream(new File(headF, headUuidName));
                IOUtils.copy(item.getInputStream(), output);
                output.close();

            }else if ("zoneImg".equals(filetype)) {

                String headZ = servlet.getServletContext().getRealPath("\\zone");
                //根据日期创建文件夹
                Date date = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/hhmmss");
                String dateString = format.format(date);
                //图片名
                String imgName = item.getName();
                //将图片存进文件
                File headFile = new File(headZ+File.separator+dateString);
                if (!headFile.exists()) {
                    headFile.mkdirs();
                }
                OutputStream output = new FileOutputStream(new File(headFile, imgName));
                IOUtils.copy(item.getInputStream(), output);
                output.close();
                //存储url
                user.getZoneImgs().add("zone"+File.separator+dateString+File.separator+imgName);
            }
        }
    }
    BeanUtils.populate(user, map);
    System.out.println(user);

    //跳转
    req.setAttribute("user", user);
    req.getRequestDispatcher("showInfo.jsp").forward(req, resp);
}

注意:

1.这里需要引入:commons-fileupload-1.2.2.jar和commons-io-2.2.jar这两个jar包,处理file文件的解析;
2.还需要引入:commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar两个jar包,将map,赋值对象;
3.处理头像名时,引入UUID,防止重名覆盖,存zoneImg根据时间创建文件夹防止重名覆盖(还不完善);
4.这里只是上的代码片段(仅展示实现思路),涉及的自定义类,需要自己定义。

总结:

在之前的某个游戏项目中,项目组在处理数据流时,没使用三方框架,自己定义数据流头七个字节,并为每个头部字节商定各自代表的意义,如第一个代表加密方式,第二个代表数据格式等,
当时最让人头疼的(现在不头疼了)是拆包,同时又涉及粘包时的拆包拼接包等问题,相当劳民伤财、、、、、、在这里处理上传file文件时,commons-fileupload-1.2.2.jar和commons-io-2.2.jar这两个jar包还是很好用的,
虽然这里跟之前游戏项目有差别,但处理的对象大致一样(流的处理)。对于成熟稳定的jar包,个人优先推荐使用!

(以上为个人学习笔记,仅供参考!)

猜你喜欢

转载自blog.csdn.net/LoveHaloK/article/details/81232288