文件上传

工具类(utils)

/**
 * 文件上传使用的工具类
 * 方法1:给图片重命名
 * 方法2:生成图片的存储路径-是要用散列算法
 */
public class UpLoadUtil {
    //生成文件名
    public static String imgReName(String fileName){
        return UUID.randomUUID().toString().replaceAll("-","")+"_"+fileName;
       // return System.currentTimeMillis()+"_"+fileName;
    }

避免同一路径下存储过多的图片 使用散列算法存储

/**
* * @param baseUrl 图片存储的基本路径,本项目对应的是WEB-INF/upload * @param fileName 图片的名字 * @return */ public static String createNewUrl(String baseUrl,String fileName){ //根据文件名来生成新路径 //一级目录:WEB-INF/upload //二级目录:WEB-INF/upload/0-15之间的一个数 //三级目录:WEB-INF/upload/0-15之间的一个数/0-15之间的一个数 int hashCode=fileName.hashCode(); //生成二级目录 int path2=hashCode & 15; //生成三级没目录 int path3=(hashCode>>4) &15; String newPath=baseUrl+"\\"+path2+"\\"+path3; File file=new File(newPath); //如果路径不存在,则创建 if(file.exists()==false){ //创建 file.mkdirs(); } return newPath; }

控制层(controller)

package com.qf.fileupload.controllers;

import com.qf.fileupload.utils.UpLoadUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UploadServlet",value = "/upload")
@MultipartConfig(maxFileSize = 1024*1024)
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //需要对request进行转换
        DiskFileItemFactory df=new DiskFileItemFactory();
        //ServletFileUpload  当普通表单标签和file在同一个表单里时,使用ServletFileUpload
        ServletFileUpload sf=new ServletFileUpload(df);
        try {
            //表单提交的所有内容都已经获取
            List<FileItem> itemList=sf.parseRequest(request);
            for (FileItem fileItem:itemList){
                //内容分两类:1、非file标签   2、file标签
                if(fileItem.isFormField()){
                    //是普通的非file标签
                    System.out.println(fileItem.getFieldName()+"======="+fileItem.getString());
                }else{
                    //说明是file标签
                    System.out.println("原名字"+fileItem.getName());
                    //获取新的文件名字
                    String newName= UpLoadUtil.imgReName(fileItem.getName());
                    //获取新的路径
                    String baseUrl="WEB-INF/upload";
                    //把相对路径转换成物理路径
                    baseUrl=request.getServletContext().getRealPath(baseUrl);
                    String newPath=UpLoadUtil.createNewUrl(baseUrl,fileItem.getName());
                    //上传
                    //创建File对象
                    File file=new File(newPath+"\\"+newName);
                    fileItem.write(file);
                    response.getWriter().print("文件上传成功!");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

页面

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2020/7/20
  Time: 9:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form method="post"  enctype="multipart/form-data" action="upload">
    <p>用户名:<input type="text" name="userName" value=""/></p>
    <p>附件1:<input type="file" name="file1" value=""/></p>
    <p><input type="submit" value="上传"/></p>
  </form>
  </body>
</html>

文件上传注意的细节:

1.安全问题

  为了保证安全最好放到WEB-INF路径下;

2、避免文件覆盖,需要生成唯一标识码拼接上图片名

3、散列存储

4、文件类型限制

List<String> nameList  = new ArrayList<String>();
    nameList.add(".jpg");
    nameList.add(".bmp");
    nameList.add(".png");
    String extName = filename.substring(filename.lastIndexOf("."));
    if(!nameList.contains(extName)){
        System.out.println("上传失败");
    return;
    }    

 

 

 

 

 
posted @ 2020-08-11 23:41  tfboys、发光少年  阅读(129)  评论(0)    收藏  举报