美文网首页
发布新闻的图文内容保存和封面图片的保存问题。

发布新闻的图文内容保存和封面图片的保存问题。

作者: yunqing_71 | 来源:发表于2019-03-01 19:48 被阅读0次

    我遇到的问题是一个网站发布新闻的显示和后台管理的问题。

    首先分析一下封面图片的保存问题:我是这么想的图片存储到服务器的D:/loadFile/newsPic路径下,然后给上传的图片文件做一个重命名,按照yyyyMMddHHmmss+6位随机字符串.png的格式,最后将这个图片的路径存储到数据库。

    先看效果:

    页面上只放了一个file文件选择,跟一个文本框name传了个“”我是图片“”

    image

    然后d盘路径下存入了我选择的图片,经过我重命名了。

    image

    看代码我打了两个断点,一个是测试name接受到我是图片了不,二是看一下重命名的名称对不对。效果如下:

    image image

    具体代码:

    <input type="file" id="newsImg" multiple="multiple" >
    
    <input type="text" id="name">
    
    <button id="aa" onclick="upload()">aa</button>
    
    function upload(){
    
    var name = $("#name").val();
    
    //js为什么这么写?额。。花儿为什么这样红?我也不知道。。请自行百度formData对象上传文件
    
     var formData = new FormData();
    
        formData.append("newsImg",document.getElementById("newsImg").files[0]);
    
        formData.append("name",$("#name").val());
    
      $.ajax({
    
            type: "post",
    
            url: "/news/uploadNewsImg",
    
            //传入组装的参数
    
            data:formData,
    
            dataType: "json",
    
            async: false,
    
            cache: false,  //上传文件不需要缓存
    
            contentType: false,  //需设置为false。因为是FormData对象,且已经声明了属性enctype="multipart/form-data"
    
            processData: false,  //需设置为false。因为data值是FormData对象,不需要对数据做处理
    
            success: function (res) {
    
                alert(res);
    
            },
    
            error:function(){
    
    
    
            }
    
        });
    

    另外激动人心的后端代码:

    @RequestMapping("/uploadNewsImg")
    
    public String studentPhotoUpload(@RequestParam(value = "newsImg") MultipartFile file,@RequestParam String name){
    
    log.info(name);
    
    if(file!=null){
    
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    
    String fileName = "news_" + dtf.format(LocalDateTime.now()) + "_" + RandomUtil.generateString(6) +".png";
    
    FileUtil.uploadFile(fileName, file);
    
    return fileName;
    
    }
    
    return null;
    
    }
    
    public static String uploadFile(String fileName, MultipartFile file) {
    
        //读取配置文件中的路径D:/uploadImgs/newsImgs    我写的路径是filepath=D:\\loadFile\\newsPic\\
    
            Resource re = new ClassPathResource("/filePath.properties");
    
            String path = null;
    
            try {
    
                Properties props = PropertiesLoaderUtils.loadProperties(re);
    
                path = props.getProperty("filepath");
    
                saveFile(path, fileName, file);
    
            } catch (IOException ex) {
    
                ex.printStackTrace();
    
            }
    
            return path;
    
        }
    
    
    
    public static void saveFile(String path, String fileName, MultipartFile file) {
    
            File targetFile = new File(path, fileName);
    
            //检测是否存在目录
    
    if (!targetFile.getParentFile().exists()) {
    
    targetFile.getParentFile().mkdirs();
    
    }
    
            try {
    
                file.transferTo(targetFile);
    
            } catch (Exception var5) {
    
                var5.printStackTrace();
    
            }
    
            System.out.println(path);
    
        }
    

    看到这里很不容易,你很优秀!你很优秀!你很优秀!重要的事说三遍,没人看自己看。
    接下来就是新闻的图文内容保存的方式了,我目前用到的方法是用一个富文本编辑器编辑好,直接把含有html标签的内容塞到数据库,可能方法比较笨,希望各位大佬把你们的方法介绍给我,谢谢,谢谢,谢谢


    image.png

    我选择的是简单轻量级的wangEditor编辑器。
    先看效果:


    image.png

    这个富文本编辑器很简单,只需引入一个js就好,具体使用看官网文档http://www.wangeditor.com/

        <div id="editor">
            <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
        </div>
        <button id="btn1">获取html</button>
    <script>
    
    var E = window.wangEditor;
    var editor = new E('#editor');
    editor.customConfig.showLinkImg = false;
    editor.customConfig.uploadFileName = 'myFileName';
    editor.customConfig.uploadImgServer = '/news/upload';
    editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
            var url =result.data;
            insertImg(url);
        }
    };
    editor.create();
    
    document.getElementById('btn1').addEventListener('click', function () {
        // 读取 html
        //alert(editor.txt.html())
        console.log(editor.txt.html());
    }, false)
    </script>
    

    后台网wangEditor上传图片的代码是

    @RequestMapping("/upload")
        public Object uploadReportFile(@RequestParam(value = "myFileName", required = false) MultipartFile cardFile,
                HttpServletRequest request) {
            //直接上传到服务器项目当中
            String path = Class.class.getClass().getResource("/").getPath();
            path = path + "static" + File.separator + "uploadfiles";
    
            Map<String, Object> map = new HashMap<>();
            if (cardFile != null) {
                String oldFileName = cardFile.getOriginalFilename();
    
                String prefix = FilenameUtils.getExtension(oldFileName);
    
                if (cardFile.getSize() > 5000000) {
                    return "1";
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis() + RandomUtil.generateString(6) + ".jpg";
                    File targetFile = new File(path, fileName);
                    // 检测是否存在目录
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
    
                    try {
    
                        cardFile.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                    String url = request.getContextPath() + "/static/uploadfiles/" + fileName;
                    map.put("errno", 0);
                    map.put("data", url);
                    return map;
                } else {
                    return "2";
                }
            }
    
            return null;
        }
    
    

    相关文章

      网友评论

          本文标题:发布新闻的图文内容保存和封面图片的保存问题。

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