SpringMVC文件上传、下载、预览、删除

记录一下做这个功能时遇到的一些问题
1、想用ajax写,其中写到onclick时报语法错误,因为传参是字符串所以加双引号,这时外面只能加单引号,要注意不可以都用双引号,不然它不清楚哪个是一对会报错。语法:onclick='upload("${}","{}","{}")'
2、ajax方式写的没有下载成功,原来是因为ajax方式请求的数据只能存放在javascipt内存空间,可以通过javascript访问,但是无法保存到硬盘,因为javascript不能直接和硬盘交互,否则将是一个安全问题。
3、响应头要写好,response.setHeader("Content-Disposition",openStyle+";filename="+ URLEncoder.encode(fileLog.getOldfilename(),"UTF-8"));不要缺少分号,Content-Disposition属性有两种类型:inline 和 attachment,inline代表直接打开就是预览,attcahment是下载,openStyle传了具体属性值。

下面贴出具体步骤和核心代码

导入依赖,commons-fileupload,commion-io,这是用来文件上传的,里边有好多类和方法用来写文件上传比较方便。
配置文件

  <!--配置文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"></property>
    </bean>

jsp页面

<!--文件上传提交方式必须是post,enctype的值必须是“multipart/form-data”-->
<form action="${APP_PATH}/fileLog/uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="subbmit" value="提交"/>
</form

controller

package com.lz.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lz.entity.FileLog;
import com.lz.service.FileLogService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/fileLog")
public class FileLogController {
    @Autowired
    private FileLogService fileLogService;

    /**
     * 查询所有文件
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
        //封装了详细的分页信息,连续显示5页
        PageHelper.startPage(pn,5);
        List<FileLog> list=fileLogService.findAll();
        PageInfo<FileLog> pageInfo=new PageInfo<>(list,5);
        model.addAttribute("pageInfo",pageInfo);
        return "success";
    }
    /**
     * 上传并保存文件
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    public void uploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response)throws Exception{
        //获取绝对路径
        String path=request.getSession().getServletContext().getRealPath("/files/");
        //每天创建一个日期文件
        String dataDir=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //获取上传文件名称
        String oldfilename=file.getOriginalFilename();
        //打开path路径下的日期文件,没有则递归创建
        File file1=new File(path,dataDir);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //获取扩展名
        String ext = FilenameUtils.getExtension(oldfilename);
        //名称唯一化
        String newfilename= UUID.randomUUID().toString().replace("-","")
                +"."+ext;
        //上传文件
        file.transferTo(new File(file1,newfilename));
        //保存文件信息
        FileLog fileLog=new FileLog();
        fileLog.setOldfilename(oldfilename);
        fileLog.setNewfilename(newfilename);
        fileLog.setExt(ext);
        fileLog.setContenttype(file.getContentType());
        fileLog.setPath("/files/"+dataDir);
        fileLog.setFilesize(String.valueOf(file.getSize()));
        //调用保存方法
        fileLogService.savefileLog(fileLog);
        //重定向到查询所有文件信息方法
        response.sendRedirect("/fileLog/findAll");

    }

    /**
     * 下载及预览文件
     * attachment为下载,inline为直接打开即预览
     * @param id
     * @param openStyle//打开方式
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/xiazai")
    public String xiazai(@RequestParam("id")Integer id,
                         String openStyle,
                         HttpServletRequest request,
                         HttpServletResponse response)throws Exception{
        System.out.println(openStyle);
        FileLog fileLog=fileLogService.findByid(id);
        //获取绝对路径
        String relpath=request.getSession().getServletContext().getRealPath(fileLog.getPath());
        //读取文件
        File file=new File(relpath,fileLog.getNewfilename());
        //设置文件响应类型
        response.setContentType(fileLog.getContenttype());
        System.out.println(file.getPath());
        //设置响应头,openStyle=attachment时为下载,inline为直接打开,下载时仍然以原文件名保存
        response.setHeader("Content-Disposition",openStyle+";filename="+ URLEncoder.encode(fileLog.getOldfilename(),"UTF-8"));
        //获取文件输入输出流
        FileInputStream in=new FileInputStream(file);
        OutputStream os=response.getOutputStream();
        //将输入流的内容拷贝给输出流
        IOUtils.copy(in,os);
        //关闭输入输出流
        in.close();
        os.close();
        return "success";
    }
        /**
     * 从数据库中和服务器目录中删除文件
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/deleteFile")
    public void deleteFile(@RequestParam("id")Integer id,
                             HttpServletRequest request,
                             HttpServletResponse response){
        FileLog fileLog = fileLogService.findByid(id);
        String newfilename = fileLog.getNewfilename();
        String path = fileLog.getPath();
        String realPath = request.getSession().getServletContext().getRealPath(path);
        File file=new File(realPath,newfilename);
        if(file.exists()){
            file.delete();
        }
        fileLogService.deleteFile(id);
        try {
            response.sendRedirect("/fileLog/findAll");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值