美文网首页
带来了解附件上传

带来了解附件上传

作者: 测试老杨 | 来源:发表于2018-03-26 17:00 被阅读76次

环境介绍

前端框架:Kendo UI
后台框架:Spring Boot + Hibernate
开发工具:IntelliJ IDEA

前端

Web页面代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>up.view.common.attachment</title>
    <script type="text/javascript" src="/assets/jquery.min.js"></script>
    <link href="/assets/styles/kendo.common.min.css" rel="stylesheet">
    <link href="/assets/styles/kendo.default.min.css" rel="stylesheet">
    <link href="/assets/styles/kendo.default.mobile.min.css" rel="stylesheet">
    <script src="/assets/kendo.all.min.js"></script>
    <script>
        $(document).ready(function () {
            if (sessionStorage.initialFiles === undefined) {
                sessionStorage.initialFiles = "[]";
            }

            var initialFiles = JSON.parse(sessionStorage.initialFiles);

            $("#files").kendoUpload({
                multiple: true,
                async: {
                    saveUrl: "http://127.0.0.1:9090/api/pic/upload",
                    removeUrl: "http://127.0.0.1:9090/api/pic/remove",
                    autoUpload: true
                },
                validation: {
                    maxFileSize: 4194304
                },
                files: initialFiles,
                success: onSuccess
            });

            function onSuccess(e) {
                var currentInitialFiles = JSON.parse(sessionStorage.initialFiles);
                for (var i = 0; i < e.files.length; i++) {
                    var current = {
                        name: e.files[i].name,
                        extension: e.files[i].extension,
                        size: e.files[i].size
                    }

                    if (e.operation == "upload") {
                        currentInitialFiles.push(current);
                    } else {
                        var indexOfFile = currentInitialFiles.indexOf(current);
                        currentInitialFiles.splice(indexOfFile, 1);
                    }
                }
                sessionStorage.initialFiles = JSON.stringify(currentInitialFiles);
            }
        });
    </script>
    <style>
        .box h4, .demo-section h4 {
            margin-bottom: 1em;
            font-size: 16px;
            line-height: 1em;
            font-weight: bold;
            text-transform: uppercase;
        }

        .demo-section
        {
            margin: 0 auto 4.5em;
            padding: 3em;
            border: 1px solid rgba(20,53,80,0.14);
        }

        .demo-hint
        {
            line-height: 22px;
            color: #aaa;
            font-style: italic;
            font-size: .9em;
            padding-top: 1em;
        }
    </style>
</head>
<body>
<div id="attachments_upload">
    <div class="box">
        <h4>附件上传</h4>
    </div>
    <div>
        <div class="demo-section k-content">
            <input name="files" id="files" type="file" />
            <div class="demo-hint">附件大小的上限为 <strong>4MB</strong>.</div>
        </div>
    </div>


</div>
</body>
</html>

附截图


image.png

后台

Controller代码如下:

package TestinStack.UnityPlatform.ctl;

import TestinStack.Core.models.UP.Attachment;
import TestinStack.Core.models.ext.ActionResult;
import TestinStack.Core.utils.ApplicationContextUtils;
import TestinStack.UnityPlatform.dao.AttachmentDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created By Yangzc 2018-03-26
 * 上传附件
 */
@Controller("TestinStack.up.upload.ctl")
@RequestMapping("api/pic/")
public class UploadCtl {

    private AttachmentDao getAttachmentDao(){
        return ApplicationContextUtils.instance.getBeanInSrv("TestinStack.up.attachment.rep");
    }

    @Value("${image.server.url}")
    private String IMAGE_SERVER_URL;

    @Value("${image.upload.path}")
    private String IMAGE_UPLOAD_PATH;

    @PostMapping("upload")
    @ResponseBody
    @Transactional
    public synchronized ActionResult fileUpload(@RequestParam("files") MultipartFile file) {
        ActionResult result = new ActionResult();
        if (file.isEmpty()) {
            return new ActionResult(false, "Please select a file to upload");
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            String fileRealName = file.getOriginalFilename();
            String ext = fileRealName.substring(fileRealName.indexOf("."));
            String fileNewName = UUID.randomUUID() + ext;
            Path path = Paths.get(IMAGE_UPLOAD_PATH + fileNewName);
            Files.write(path, bytes);
            String url = IMAGE_SERVER_URL + fileNewName;
            //响应上传图片的url
            Map map = new HashMap<>();
            map.put("error", 0);
            map.put("url", url);
            result.setContent(map);
            Attachment attachment = new Attachment();
            attachment.setAtName(file.getOriginalFilename());
            attachment.setAtFilePath(url);
            getAttachmentDao().save(attachment);
            return result;
            //return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new ActionResult(false, "file upload failed.");
        }

    }

    @PostMapping("remove")
    @ResponseBody
    public ActionResult fileUpload(@RequestParam("fileNames") String fileName) {
            return new ActionResult(true, fileName + "has been deleted successfully.");
    }

}

附截图


image.png

测试结果

image.png image.png image.png image.png

相关文章

网友评论

      本文标题:带来了解附件上传

      本文链接:https://www.haomeiwen.com/subject/pubrcftx.html