SSM框架下文件的上传下载(无内容时js弹窗提示)

SSM框架下文件的上传下载

非全部原创,仅用来记录学习过的内容,自己添加了js判空弹窗的功能

1.首先我们创建一个测试用的jsp页面,代码如下。
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>文件上传下载title>
head>
<body>
    <form action="http://localhost:8080/uploadDemo/rest/file/upload" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file" width="120px">
        <input type="submit" value="上传">
    form>
    <hr>
    <form action="http://localhost:8080/uploadDemo/rest/file/down" method="get">
        <input type="submit" value="下载">
    form>
body>
html>
2.在我们的maven项目的pom.xml文件中添加fileupload文件上传下载jar包,不然后面的操作可能会报错,如下。

<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3version>
dependency>
3.在sring的servlet视图解析器下面定义CommonsMultipartResolver文件解析器,就是加入这个的时候运行项目,如果没有fileuload相关的jar包就会报错。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    
    <property name="defaultEncoding" value="utf-8">property>
     
    <property name="maxUploadSize" value="5242440">property>  
bean>
4.在controller层写上springmvc上传下载的代码,如下。
package com.baidu;
@RequestMapping("file")
@Controller
public class FileController {
    /**
     * 文件上传功能
     * @param file
     * @return
     * @throws IOException 
     */
    @RequestMapping(value="/upload",method=RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();  
        File dir = new File(path,fileName);        
        if(!dir.exists()){
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);
        return "ok!";
    }

    /**
     * 文件下载功能
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/down")
    public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //模拟文件,myfile.txt为需要下载的文件
        String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt";
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
        //假如以中文名下载的话
        String filename = "下载文件.txt";
        //转码,免得文件名中文乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);  
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型  
        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();
    }
}

springmvc上传下载很方便,代码直接复制使用。

5.在使用时发现未选择文件仍会存入后台数据库,因此加入了一个js弹窗,未选择文件时提示
<form action="" onsubmit="return checkfile()"
method="post" enctype="multipart/form-data">    
    <div>
        <label style="width:80px;float:left;margin-top:15px;">选择文件:label> 
        <input class="logininput" style="width:200px;float:left;margin-top:12px;" type="file" id="file">
        <button  type="submit"
            style="float:left;width:80px;float:left;margin-top:12px;margin-left:10px">上传button>
    div>
form>

<script>
function checkfile() {
    var file = document.getElementById('file');;    
    if (file.value == '' || file.value == undefined || file.value == null) {
        alertmsg("未选择文件!", 'warning');
        return false;
    } else {
        return ture;
    }
}
script>

你可能感兴趣的:(SSM)