javaweb 上传下载(二)

本文介绍了一个使用SpringMVC实现的文件上传和下载功能。通过表单提交多个文件和一个文本字段,并将文件存储到服务器指定路径。此外,还提供了根据ID加载并下载已上传文件的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

form表单

         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>文件上传</title>
</head>
<body>
<form id="subdata" action="${contextPath}/autoLoad" enctype="multipart/form-data" method="post">
    报告文件1:<input type="file" name="files"><br/>
    报告文件2:<input type="file" name="files"><br/>
    报告文件3:<input type="file" name="files"><br/>
    机器信息:<input type="text" name="string"><br/>
    <input type="submit" value="提交">
</form>
<%--<iframe name="iUpload"  style="display:none"></iframe>--%>
</body>

springMVC上传下载

public class FileHandleController extends BaseController {
    private static Log log = LogFactory.getLog(FileHandleController.class);
    @Autowired
    private SpotRecordService spotRecordService;

    @RequestMapping("/fileHandle")
    public String home() {
        return "fileHandle";
    }

    //实现多文件,单字符串解析上传,对文件进行用springmvc来上传,
    @RequestMapping("/autoLoad")
    public void uploadFile(@RequestParam CommonsMultipartFile[] files, HttpServletRequest req, HttpServletResponse resp, String string) throws ServletException,IOException {
        log.debug("进入uploadFile");
        System.out.println(string);
        if (StringUtil.isNotBlank(string)) {
            String paramStr = JsonUtils.toJson(string);
        }
        long start = System.currentTimeMillis();

        System.out.println(start);

        String savePath = req.getSession().getServletContext().getRealPath("/WEB-INF/upload");
        //String savePath = req.getRealPath("/WEB-INF/upload");
        log.debug("保存的路径" + savePath);
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath + "目录不存在,需要创建");
            file.mkdir();
        }
        if (files !=null && files.length>0){
            for (int i=0; i<files.length;i++){
                try {
                    String logname = i + "_log.txt";
                    files[i].transferTo(new File(savePath+ "/" + logname));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        long end = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(Calendar.getInstance().getTime());
        SpotRecordBO spotRecordBO = JsonUtils.toObject(string,SpotRecordBO.class);
        spotRecordBO.setUpdateTime(time);
        log.debug(req.getRequestURL() + "\n" + spotRecordBO.toString());
        spotRecordService.insertSpotRecord(spotRecordBO);
    }

    @RequestMapping("/loadFile")
    public void loadFile(@Param("id") Integer id, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器 host地址+ "/WEB-INF/upload/123.txt"(recordUrl 格式);
        //完整下载地址 "/WEB-INF/upload/123.txt";
        SpotRecordBO spotRecordBO = spotRecordService.getBySpotRecordId(id);
        String recordUrl = spotRecordBO.getRecordUrl();
        String fileName = recordUrl.substring(recordUrl.lastIndexOf("/") + 1);
        String fileSaveRootPath = req.getSession().getServletContext().getRealPath("/WEB-INF/upload");
        //String fileSaveRootPath = req.getRealPath("/WEB-INF/upload");
        String path = findFileSavePathByFileName(fileName, fileSaveRootPath);
        File file = new File(path + "\\" + fileName);
        log.debug("文件路径" + file.getPath());
        if (!file.exists()) {
            //req.getRequestDispatcher("/message.jsp").forward(req, resp);
            log.debug("文件不存在");
            return;
        }
        try {
            FileInputStream in = new FileInputStream(path + "\\" + fileName);
            OutputStream out = resp.getOutputStream();
            resp.setContentType("application/force-download");
            resp.setContentType("application/octet-stream");
            resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //FileInputStream in = new FileInputStream("http://172.20.112.139:8080//test//downFile//"  + fileName);
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                out.flush();
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String findFileSavePathByFileName(String fileName, String fileSaveRootPath) {
        String dir = fileSaveRootPath + "\\";
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dir;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值