Java-Maven实现简单的文件上传下载(菜鸟一枚、仅供参考)


1、JSP页面代码实现

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


"Content-Type" content="text/html; charset=UTF-8">
UploadDown


<%
    if(null==session.getAttribute("currentUser")){
        System.out.print("ddd");
        response.sendRedirect("/login");
        return;
    }else{
        System.out.print("yyy");
    }
 %>
"center">
"${pageContext.request.contextPath }/file/upload" method="post" enctype="multipart/form-data"> "file" name="file" width="120px"> "submit" value="上传">

"1px" bordercolor="yellow" align="center"> "${fileList }" var="file" varStatus="s"> "dateValue" class="java.util.Date"/> "dateValue" property="time" value="${file.lastModified()}"/>
"5" style="font-size: 25px">目录下可下载文件
"66px">序号 "150px">文件 "150px">大小 "200px">上传时间 "150px">下载
"center">${s.count} "center">${file.getName() } "center"> "number" value="${file.length()/1024.00}" pattern="#0.00"/> KB "center"> "${dateValue}" pattern="yyyy-MM-dd HH:mm:ss"/> "center"> "button" value="下载" onclick="window.location.href='${pageContext.request.contextPath }/file/down?filename=${file.getName()}'"> "button" value="删除" onclick="window.location.href='${pageContext.request.contextPath }/file/deleteFile?filename=${file.getName()}'"> <%-- --%>
"canvas" style="position: fixed;"> <script src="./js/js1.js"></script>

2、上传下载代码实现

package com.chao.controller;

import com.chao.utils.PathUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

@Controller
@RequestMapping({ "file" })
public class UploadDownController {
    @RequestMapping
    public String toIndex(Model model) throws Exception {
        String path = PathUtil.static_root;
        File file = new File(path);
        List fileList = new ArrayList();

        if (file != null) {
            if (file.isDirectory()) {
                File[] fileArray = file.listFiles();
                if ((fileArray != null) && (fileArray.length > 0))
                    for (File f : fileArray)
                        fileList.add(f);
            } else {
                System.out.println("目录不存在!");
            }
        }
        model.addAttribute("fileList", fileList);
        model.addAttribute("path", path);
        return "index";
    }

    @RequestMapping(value = { "upload" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartRequest multipartRequest = (MultipartRequest) request;
        MultipartFile file = multipartRequest.getFile("file");

        if ((file == null) || (file.isEmpty())) {
            response.setCharacterEncoding("GB2312");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('请选择上传文件!'); window.location='/file' </script>");
            out.flush();
            out.close();
        } else {
            String fileName = file.getOriginalFilename();
            String path = PathUtil.static_root;

            File dir = new File(path, fileName);
            if (!dir.getParentFile().exists()) {
                dir.getParentFile().mkdirs();

                dir.createNewFile();
            } else {
                dir.createNewFile();
            }

            file.transferTo(dir);
            response.sendRedirect("/file");
        }
    }

    @RequestMapping({ "down" })
    public void down(String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = PathUtil.static_root;
        String downFileName = new String(filename.getBytes("ISO8859-1"), "utf-8");

        String fileName = path + File.separator + downFileName;

        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("multipart/form-data");

        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while ((len = bis.read()) != -1) {
            out.write(len);
            out.flush();
        }
        out.close();
    }

    @RequestMapping({ "deleteFile" })
    public String deleteFile(String filename) throws Exception {
        String path = PathUtil.static_root;
        filename = new String(filename.getBytes("ISO8859-1"), "utf-8");
        String fileName = path + File.separator + filename;

        File file = new File(fileName);
        if ((file.exists()) && (file.isFile()))
            file.delete();
        else {
            return "error";
        }
        return "redirect:/file";
    }
}

3、文件上传环境路径判断

package com.chao.utils;

public class PathUtil {

    public static final String WINDOWS_STATIC = "C:\\testfile\\file";// Windows静态文件路径

    public static final String LINUX_STATIC = "/testfile/file";// Linux静态文件路径

    public static String static_root = null;

    static {
        String system = System.getProperties().getProperty("os.name"); // 获取系统类型
        if (system.contains("Windows"))
            static_root = WINDOWS_STATIC;
        if (system.contains("Linux"))
            static_root = LINUX_STATIC;
    }
}