spring mvc 文件上传下载

最近在做项目涉及了文件的上传下载,使用的框架为Springboot。上传使用的框架是easyUpload。

上代码!

上传前台html:

$('#easyContainer').easyUpload({
allowFileTypes : '*.jpg;*.docx;*.pdf',//允许上传文件类型,格式';*.doc;*.pdf'
allowFileSize : 100000,//允许上传文件大小(KB)
selectText : '选择文件',//选择文件按钮文案
multi : true,//是否允许多文件上传
multiNum : 5,//多文件上传时允许的文件数
showNote : true,//是否展示文件上传说明
note : '提示:最多上传5个文件,支持格式为doc、pdf、jpg',//文件上传说明
showPreview : true,//是否显示文件预览
url : '../assignment/addThesis_Assignment?t_id='+selectContent[0].t_id+'&t_name='+selectContent[0].t_name,//上传文件地址
fileName : 'file',//文件filename配置参数


formParam : {
token : $.cookie('token_cookie'),
//不需要验证token时可以去掉
},//文件filename以外的配置参数,格式:{key1:value1,key2:value2}
timeout : 30000,//请求超时时间
successFunc : function(res) {
console.log('成功回调', res);
},//上传成功回调函数
errorFunc : function(res) {
console.log('失败回调', res);
},//上传失败回调函数
deleteFunc : function(res) {
console.log('删除回调', res);
}//删除文件回调函数

});

只是测试了成功的回调。

上传后台:

        @ResponseBody
@RequestMapping("addThesis_Assignment")

public Map<String, Object> addThesis_Assignment(

@RequestParam("file") MultipartFile file,

HttpServletRequest request, int t_id, String t_name) {
Map<String, Object> map = new HashMap<String, Object>();
Thesis_Assignment thesis_Assignment = new Thesis_Assignment();
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
String filePath = request.getSession().getServletContext()
.getRealPath("assignmentUpload/");
String filename1 = fileName.substring(fileName.indexOf("."));
fileName = t_name + "任务书" + filename1;
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
thesis_Assignment.setT_id(t_id);    //这些是我自己要用到的实体类
thesis_Assignment.setIsUpload(0);
thesis_Assignment.setThesis_assignment_name(fileName);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
thesis_Assignment.setThesis_assignment_date(sdf.format(new Date()));
// 得到session中存储的数据
UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
"userInfo");
// 使用session中的数据查询教师表得到教师的相关信息
TeacherInfo teacher = assignmentServiceImpl.getTeacher(userInfo
.getUsername());
thesis_Assignment.setUser_name(teacher.getTeacher_name());
// 当上传文件时后台对数据库做的是更新操作
// 更新上传文件名称与上传时间和上传者
int a = assignmentServiceImpl

.updateThesis_Assignment(thesis_Assignment);

                //上传成功后将code=200返回到前台其他的两个可能是没有什么用处的  但是没有测试。

map.put("contentType", contentType);
map.put("fileName", fileName);

map.put("code", 200);    //主要的

                //必须返回map集合

return map;
}

下载前台html:

var urlString = "http://localhost:8080/assignmentUpload/"+selectContent[0].thesis_assignment_name+"";

//你要下载文件的存放路径与文件名称还有文件的格式    loaction.href=“”跳到后台Controller

location.href = "../download?urlString=" + urlString;

下载后台:

@ResponseBody
@RequestMapping("download")
    public void download(HttpServletRequest request,HttpServletResponse response,String urlString){
        BufferedInputStream dis = null;
        BufferedOutputStream fos = null;


        
        String fileName = urlString.substring(urlString.lastIndexOf('/') + 1);


        try {
//         通过给定的字符串创建URL路径
            URL url = new URL(urlString);
//           application/octet-stream 代表 ./ (二进制流,不知道下载文件类型)
//            作用是使客户端浏览器分区不同种类的数据,并根据()内字符调用浏览器内部不同的
//            潜入模块来处理相应的数据。
            response.setContentType("application/octet-stream");
//            Content-disposition作用是告诉浏览器这个文件的名字和类型
//            在设置setHeader(“Content-disposition”)之前先设置setContentType();
//            sttachment设置弹窗
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
//            response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));


            dis = new BufferedInputStream(url.openStream());
            fos = new BufferedOutputStream(response.getOutputStream());


            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
                fos.write(buff, 0, bytesRead);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dis != null)
                try{
                    dis.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            if (fos != null)
                try{
                    fos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }


        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值