舒大少博客

一个95后少年的个人博客

当前时间为:
欢迎大家来到舒大少博客https://www.9713job.com,广告合作以及淘宝商家推广请微信联系15357240395

文件上传

2022-04-28 16:57:59
swq1822677238

手机扫码查看

文件上传

upload工具类

public class UploadUtils {
    // 生成带有UUID新的文件名
    public static String newFileName(String filename){
        return UUID.randomUUID().toString().replaceAll("-","")+"_"+filename;
    }
    // 生成二级、三级目录
    public static String newFilePath(String basePath,String fileName){
        int hashCode = fileName.hashCode();
        int path1=hashCode&15;
        int path2=(hashCode>>4)&15;
        String newPath=basePath+ File.separator+path1+File.separator+path2;
        File file=new File(newPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return newPath;
    }
}

控制层

// 文件上传
@RequestMapping("/uploads")
@ResponseBody
public String uploads(HttpServletRequest request,HttpServletResponse response)throws Exception{
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");

    String username = request.getParameter("username");
    Part part = request.getPart("file1");

    String uploadPath = request.getServletContext().getRealPath("WEB-INF/upload");
    File file=new File(uploadPath);
    if (!file.exists()) {
        file.mkdirs();
    }

    String oldFileName = part.getSubmittedFileName();
    String newFileName = UploadUtils.newFileName(oldFileName);

    String newFilePath = UploadUtils.newFilePath(uploadPath, oldFileName);

    part.write(newFilePath+File.separator+newFileName);
    return "上传成功";
}
// 文件列表
@RequestMapping("/fileList")
public String fileList(HttpServletRequest request){
    HashMap<String,String> fileMap=new HashMap<>();
    String basePath=request.getServletContext().getRealPath("WEB-INF/upload");
    DownLoadUtils.getFileList(new File(basePath),fileMap);

    request.setAttribute("fileMap",fileMap);
    return "fileList";
}

下载工具类

public class DownLoadUtils {
    public static void getFileList(File file, HashMap<String,String> fileMap){
        File[] files = file.listFiles();
        if (files!=null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    getFileList(f,fileMap);
                }else{
                    String filename = f.getName();
                    String realName = filename.substring(filename.indexOf("_") + 1);
                    fileMap.put(filename,realName);
                }
            }
        }
    }
}

下载控制层

// 文件下载
@RequestMapping("/download")
public void download(String filename,HttpServletRequest request,HttpServletResponse response) throws IOException {
    String basePath = request.getServletContext().getRealPath("WEB-INF/upload");

    String realName = filename.split("_")[1];
    String downPath = UploadUtils.newFilePath(basePath, realName);

    response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));

    FileInputStream is=new FileInputStream(downPath+File.separator+filename);
    ServletOutputStream os=response.getOutputStream();
    byte[] buffer=new byte[1024*1024*100];
    int len=0;
    while ( (len=is.read(buffer))!=-1 ){
        os.write(buffer,0,len);
    }
    os.close();
    is.close();
}

文件下载页面

<table border="1">
    <tr>
        <td>文件名</td>
        <td>操作</td>
    </tr>
    <c:forEach items="${requestScope.fileMap}" var="map">
        <tr>
            <td>${map.value}</td>
            <td><a href="${pageContext.request.contextPath}/uploads/download?filename=${map.key}">下载</a></td>
        </tr>
    </c:forEach>
</table>

文件上传页面(layui框架)

<button type="button" class="layui-btn" id="test1">
    <i class="layui-icon">&#xe67c;</i>上传图片
</button>

<script>
    layui.use('upload', function(){
        var upload = layui.upload;

        //执行实例
        var uploadInst = upload.render({
            elem: '#test1' //绑定元素
            ,url: '/uploads/uploads' //上传接口
            ,field: 'file1'
            ,accept: 'images'
            ,acceptMime: 'image/*'
            ,done: function(res){
                //上传完毕回调
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });
</script>

发表评论

邮箱地址不会被公开。 必填项已用*标注