ssm 文件上传和下载

下载:

后台代码:
 

package com.guangyxy.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileDownUtils {
    
    
    /**  
     * 文件下载功能  
     * @param request  
     * @param response  
     * @throws Exception  
     */  
    public static void down(String fileUrlName,HttpServletRequest request,HttpServletResponse response) throws Exception{  
        //获取输入流  
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileUrlName)));  
        
        int index = fileUrlName.lastIndexOf("/");

        //截取原文件名字
        String filename = fileUrlName.substring(index+1);
        
        //转码,免得文件名中文乱码  
        filename = URLEncoder.encode(filename,"UTF-8");  
        //设置文件下载头  
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型    
        response.setContentType("multipart/form-data");
        ServletOutputStream outputStream = response.getOutputStream();
        BufferedOutputStream bout = new BufferedOutputStream(outputStream);  
        int len = 0;  
        while((len = bis.read()) != -1){  
            bout.write(len);  
            bout.flush();  
        }
        
        bout.close();
      
    }   
}

js代码

// 文件下载

因为ajax不能传io流,而且还要根据后台返回情况作提示信息,所以还用ajax请求后台查询文件是否存在,如果存在

则 用document.location.href = url1再次请求后台下载文件。url为后台查看文件是否存在的路径,url1为后台下载文件路径
 

function fileDown(url, url1) {
    /*
     * var url ="/mainContro/fileDown" document.location.href=url;
     */
    $.ajax({
        type : 'post',
        url : url,
        data : null,
        async : true,
        success : function(data) {
            if (data == "success") {
                document.location.href = url1;
            } else {
                layer.msg("模板不存在", {
                    icon : 5,
                    time : 1000
                })
            }
        }
    })
}

上传

后台代码:

package com.guangyxy.tool;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

import com.guangyxy.tool.DBInfoUtils;
public class FileUploadUtils  {

	public static File upload(MultipartFile file, HttpServletRequest request) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());

        // uploads文件夹位置
        String rootPath = new DBInfoUtils("config.properties").getValue("uploadFilePath");
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        
        // 新文件名
        String newFileName = res + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 创建年月文件夹
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
        String dir = sdf1.format(new Date());
        //年月日文件夹
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        String zdir = sdf2.format(new Date());
        File dateDirs = new File(dir + File.separator + zdir);

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在,则创建父目录
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        // 将内存中的数据写入磁盘
        file.transferTo(newFile);
       
        return  newFile;
    }
	
}

js代码

// 上传文件
function fileUpload(id, url) {
	if ($(document.getElementById(id)).val() != "") {
		/* formSubmit('../../mainContro/fileupload','_self'); */
		var uploadFile = new FormData($("#fileUploadForm")[0]);
		if ("undefined" != typeof (uploadFile) && uploadFile != null
				&& uploadFile != "") {
			$.ajax({
				url : url,
				type : 'POST',
				data : uploadFile,
				async : false,
				cache : false,
				contentType : false, // 不设置内容类型
				processData : false, // 不处理数据
				success : function(data) {
					if (data == "success") {
						layer.msg("上传成功", {
							icon : 6,
							time : 1000
						});
					} else {
						layer.msg("上传失败", {
							icon : 5,
							time : 1000
						});
					}
				}
			})
		} else {
			layer.msg("选择的文件无效!请重新选择", {
				icon : 2,
				time : 1000
			});
		}
	}
}

另为了好看你可以点击<a>标签或者<button>按钮触发一个函数,函数内部打开<input type="file">框的函数,具体操作如下:

<!--html -->
<form id="fileUploadForm" method="post" enctype="multipart/form-data">
    <input type="file" name="file" style="display: none;" id="fileId" onchange="ResumeFileupload();"></input>
   <a style="background-color: #B6FFDE;" href="#" onclick="filePop('fileId');">上传</a>
</form> 

//选择文件弹出框
function filePop(id){
	document.getElementById(id).click();
     }

// 简历上传
function ResumeFileupload() {
	var url = '/mainContro/ResumeFileupload';
	var id = "fileId";
	fileUpload(id, url);
}

因为我有多处不同的文件上传和下载,所以我把js中上传和下载函数变化的部分提取了出来!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小一猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值