前端上传图片文件预览,并且删除下载

前端上传文件,并且删除下载

废话不多说,直接上干货

简单版

第一步, 在pom.xml中添加依赖

commons-fileupload.jar通常和commons-io.jar包一起使用的。用来操作文件上传。里面封装了很多上传的功能,大大简化了我们写上传代码的复杂性。

 <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons-io.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>

第二步, 前端from表单提交

<html lang="en">
<script type="text/javascript">
    var ctx = '${pageContext.request.contextPath}';
</script>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${ctx}/file/uploadFile" enctype="multipart/form-data">
    选择文件:<input type="file" name="file">
    <input type="submit" value="Upload">提交!
</form>

</body>
</html>

注意:from表单中的enctype="multipart/form-data"必须写,否则报错

org.springframework.web.multipart.MultipartException: The current request is not a multipart request

*第三步, 后端定义文件上传的方法,前端点击提交之后,会在D:/test/tmpFiles中有test.png的文件,你上传的是什么文件,在目录下就会是什么文件,我这里上传的是test.png的文件

package com.centrin.test.file;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
@RequestMapping("/file")
public class FileUploadController {

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                //文件存放服务端的位置
                String rpptPath = "D:/test";
                File dir = new File(rpptPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();//自动创建目录
                //写文件到服务器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);
                return "您成功上传文件=" + file.getOriginalFilename();

            } catch (Exception e) {
                return "上传失败 " + file.getOriginalFilename() + " => " + e.getMessage();
            }
        } else {
            return "您上传失败了" + file.getOriginalFilename() + "因为文件是空的";
        }
    }
}

走到这里,普通的文件上传就实现了!

进阶版 (连接数据库)

第一步,依旧是在pom.xml中添加上述两个依赖,这里就不二次展示了。

第二步,在spring-mvc.xml中配置下列内容,通过StandardServletMutipartResolver解析mutipart请求,DispatchServlet自己并不负责去解析mutipart 请求,而是委托一个实现了MultipartResolver接口的类来解析mutipart请求

<!-- 定义JSP -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/views/" />
	<property name="suffix" value=".jsp" />
	<property name="redirectHttp10Compatible" value="false" /> <!-- 解决 https redirest 问题-->
</bean>

<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

第三步,前端写上传文件的页面,引入uploader的js和css,下载链接https://www.openzui.com

<body>
<link rel="stylesheet" href="${ctx}/static/plugins/zui/lib/uploader/zui.uploader.min.css"/><!--加载效果 start-->
<link rel="stylesheet" href="${ctx}/static/plugins/zui/lib/uploader/zui_uploader.css"/><!--加载效果 start-->
<div id="preloader">
    <div id="status">
        <i class="fa fa-spinner fa-spin"></i>
    </div>
</div>
<html>
<head>
    <title>Title</title>
</head>
<body>
<section>
    <div class="mainpanel_mian">
<form class="form-horizontal" method="post" id="main_form" autocomplete="off">
    <div class="form-group col-sm-4">
        <label class="control-label col-sm-4 required">文件:</label>
        <div class="col-sm-8">
            <div id='businessUploader' class="uploader">
                <div class="uploader-message text-center">
                    <div class="content"></div>
                    <button type="button" class="close">×
                    </button>
                </div>
                <div class="uploader-files file-list file-list-grid"></div>
                <div>
                    <button type="button"
                            class="btn btn-link uploader-btn-browse">
                        <i class="icon icon-plus"></i> 选择文件
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>

    </div>
</section>
<div style="display: none">
    <textarea id="file2" style="display: none">${file2}</textarea>
</div>
<script src="${ctx}/static/plugins/zui/js/zui.js"></script>
<script src="${ctx}/static/plugins/zui/lib/uploader/zui.uploader.min.js"></script>
<script src="${ctx}/static/file/uploadFile.js"></script>

</body>

uploadFile.js为下方代码,复制导入即可

var businessFiles = [];
$(function () {

    //营业执照
    $('#businessUploader').uploader({
        autoUpload: true,            // 当选择文件后立即自动进行上传操作
        url: ctx + '/file/uploadFile/2',  // 文件上传提交地址,不加水印
        previewImageSize: {width: 100, height: 140},//预览图像大小
        deleteActionOnDone: function (file, doRemoveFile) {
            for (var i in businessFiles) {
                if (businessFiles[i].id == file.id) {
                    businessFiles.splice(i, 1)
                }
            }
            doRemoveFile();
        },
        lang: 'zh_cn',
        limitFilesCount: 1,
        uploadedMessage: false,
        deleteConfirm: true,
        previewImageIcon: true,
        rename: true,
        staticFiles: businessFiles,
        filters: {
            // 只允许上传图片或图标(.ico)
            mime_types: [
                {title: '图片', extensions: 'jpg,gif,png,jpeg'}
            ],
            // 最大上传文件为 10MB
            max_file_size: '10mb',

            // 不允许上传重复文件
            prevent_duplicates: true
        },
        onFileUploaded: function (file, responseObject) {
            var response = eval('(' + responseObject.response + ')');
            if (response.result != null && response.result != "undefined" && response.result == "success") {
                businessFiles.push(file);
            }
        }
    });
});

到这一步,前端页面就已经完成,前端效果图如下。点击选择之后,会进入uploadFile.js,通过url进入后端,将文件保存到数据库中
在这里插入图片描述
第四步,将文件上传到服务器上,并且返回文件的id,成功标识,下载路径

/**
     * 上传附件
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadFile/{type}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(@PathVariable("type") Integer type,
                                          @RequestParam MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(3);
        if (file == null) {
            map.put("message", "文件内容为空");
            map.put("result", "failed");
            return map;
        }
        try {
            String oriFilename = file.getOriginalFilename();

            String fileId = UUID.randomUUID().toString().replaceAll("-", "")
                    + oriFilename.substring(oriFilename.indexOf("."));

            String folderPath = Constant.FILE_ROOT_PATH + "/" + DateUtils.getDate() + "/";
            if (!FileUtil.isExistingFolder(new File(folderPath))) {
                //创建目录
                FileUtil.mkdirs(folderPath);
            }
            String filePath = folderPath + fileId;

            FileUtil.writeBytes(filePath, file.getBytes());
            String contentType = file.getContentType();
            //将文件添加到FilesEntity 的类,用来存放文件内容
            FilesEntity entity = new FilesEntity();
            entity.setCreateTime(DateUtils.getDateTime());
            entity.setDelFlag(filesEn0);
            entity.setTitle(oriFilename);
            entity.setPath("/" + DateUtils.getDate() + "/" + fileId);
            entity.setFileType(contentType);
            entity.setType(type);
            entity.setFileSize(String.valueOf(file.getSize()));
            this.fileService.add(entity);

            map.put("id", entity.getId());
            map.put("result", "success");
            map.put("url", request.getContextPath() + "/file/downloadFile/" + entity.getId() + "");
        } catch (Exception e) {
            logger.error("文件上传", e);
            map.put("message", "上传文件错误");
            map.put("result", "failed");
        }
        return map;
    }

此刻,文件就已经上传,并且存在了数据库中,效果图如下
在这里插入图片描述
点击下载按钮,通过后端返回的下载路径,就可以直接将刚刚上传的文件下载到本地

 /**
     * 下载附件
     *
     * @param id
     * @param response
     */
    @RequestMapping(value = "/downloadFile/{id}", method = RequestMethod.GET)
    public void downloadFile(@PathVariable("id") Integer id, HttpServletResponse response) {
        //设置Content-Disposition
        FilesEntity entity = this.fileService.findById(FilesEntity.class, id);
        String fileName = entity.getTitle();
        String fileId = entity.getPath();
        String folderPath = Constant.FILE_ROOT_PATH;
        String filePath = folderPath + fileId;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //文件输入流java.io.FileInputStream类继承自字节输入流InputStream类,表示从文件中读取二进制数据到程序中:
            inputStream = new FileInputStream(filePath);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            response.flushBuffer();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new SysException("server error.");
        } finally {
            //关闭流
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }

不好的地方大家多多指出。
觉得不错的话点个赞吧,希望更多的人看得到!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值