• 使用Webupload上传图片到FastDFS分布式文件系统


    使用Webupload插件上传图片到FastDFS分布式文件系统。

    前提条件:1.已安装FastDFS分布式文件系统

                      2.使用webuploader插件上传文件

                      3.maven工程已引入FastDFS依赖

    图片上传及图片回显部分代码如下:

    <!-- 添加商品页面 -->
    
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <base th:href="|${#request.getContextPath()}/|"/>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <link rel="stylesheet" href="resources/css/reset.css" type="text/css"
              media="screen" />
        <link rel="stylesheet" href="resources/css/style.css" type="text/css"
              media="screen" />
        <link rel="stylesheet" href="resources/css/invalid.css" type="text/css"
              media="screen" />
        <script type="text/javascript"
                src="resources/scripts/jquery-1.8.3.min.js"></script>
    
        <!-- 引入上传控件 webuploader -->
        <link rel="stylesheet" href="resources/widget/webuploader/webuploader.css" type="text/css"
              media="screen" />
        <script type="text/javascript" src="resources/widget/webuploader/webuploader.min.js"></script>
    
        <script>
            var uploader;
            $(function(){
                //初始化webuploader插件
                uploader = WebUploader.create({
                    // 选完文件后,是否自动上传。
                    auto: false,
                    // swf文件路径
                    swf: 'resources/widget/webuploader/Uploader.swf',
                    // 文件接收服务端。
                    server: '/imgs/uploader',
                    // 选择文件的按钮。可选。
                    // 内部根据当前运行是创建,可能是input元素,也可能是flash.
                    pick: '#filePicker',
                    // 只允许选择图片文件。
                    accept: {
                        title: 'Images',
                        extensions: 'gif,jpg,jpeg,bmp,png',
                        mimeTypes: 'image/*'
                    }
                });
    
                //给webuploader绑定事件
                //fileQueued  当文件被加入队列以后触发
                uploader.on("fileQueued",function (file) {
                    //生成图片缩略图
                    uploader.makeThumb( file, function (error ,ret) {
                        if(error){
                            alert(file.name+"缩略图生成失败")
                        }else{
                            //将缩略图展示到预览图div中
                            var img = "<img src=""+ret+"" style="height: 100px;  100px; margin-right: 5px;"/>"
                            $("#imgs_div").append(img);
                        }
                        
                    }, 100, 100 )
                });
    
                //给webupload绑定成功事件
                uploader.on("uploadSuccess",function (file,response) {
                    var val = $("#image_paths").val();//获取images_path标签值
                    if(val.length > 0){
                        val += "|";
                    }
                    val += response.imgUrl;
                    $("#image_paths").val(val);//设置images_path标签值
                })
            });
    
            /**
             * 上传图片
             */
            function upload_imgs(){
                if(uploader){
                    uploader.upload();
                }
            }
        </script>
    
    </head>
    <body>
    <div id="main-content">
        <div class="content-box">
            <div class="content-box-content">
                <div class="tab-content default-tab" id="tab2">
                    <form action="/goods/insert" method="post">
                        <fieldset>
                            <!-- Set class to "column-left" or "column-right" on fieldsets to divide the form into columns -->
                            <p>
                                <label>商品名称</label> <input
                                    class="text-input small-input" type="text"
                                    name="gname" />
                            </p>
                            <p>
                                <label>商品图片</label>
                                <!--dom结构部分-->
                                <div id="uploader-demo">
                                    <!-- 存放上传图片的预览图 -->
                                    <div id="imgs_div" style="border: solid 1px #D0D0D0;  500px; height: 120px; margin-bottom: 10px; padding: 20px;">
                                       <!-- <img src="xxx" style="height: 100px;  100px; margin-right: 5px;"/>
                                        <img src="xxx" style="height: 100px;  100px; margin-right: 5px;"/>
                                        <img src="xxx" style="height: 100px;  100px; margin-right: 5px;"/>
                                        <img src="xxx" style="height: 100px;  100px; margin-right: 5px;"/>-->
                                    </div>
                                    <button type="button" class="mybutton" style="margin-bottom: 10px;" onclick="upload_imgs();">上传图片</button>
                                    <div id="filePicker">选择图片</div>
                                    <input id="image_paths" type="hidden" name="gimage" value=""/>
                                </div>
                            </p>
                            <p>
                                <label>商品价格</label> <input
                                    class="text-input small-input" type="text"
                                    name="gprice" />
                            </p>
                            <p>
                                <label>商品库存</label> <input
                                    class="text-input small-input" type="text"
                                    name="gsave" />
                            </p>
                            <p>
                                <label>商品的描述</label>
                                <textarea class="text-input textarea wysiwyg"
                                          name="ginfo" cols="79" rows="15"></textarea>
                            </p>
                            <p>
                                <input class="mybutton" type="submit" value="提交" />
                            </p>
                        </fieldset>
                        <div class="clear"></div>
                        <!-- End .clear -->
                    </form>
                </div>
                <!-- End #tab2 -->
            </div>
            <!-- End .content-box-content -->
        </div>
    </div>
    <!-- End #main-content -->
    </body>
    </html>
    <!-- 商品列表页面 -->
    
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <base th:href="|${#request.getContextPath()}/|"/>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <!-- Reset Stylesheet -->
        <link rel="stylesheet" href="resources/css/reset.css" type="text/css"
              media="screen" />
        <!-- Main Stylesheet -->
        <link rel="stylesheet" href="resources/css/style.css" type="text/css"
              media="screen" />
        <link rel="stylesheet" href="resources/css/invalid.css" type="text/css"
              media="screen" />
        <script type="text/javascript"
                src="resources/scripts/jquery-1.3.2.min.js"></script>
        <!-- jQuery Configuration -->
        <script type="text/javascript"
                src="resources/scripts/simpla.jquery.configuration.js"></script>
    </head>
    <body>
    <div id="main-content">
        <div class="content-box">
            <!-- End .content-box-header -->
            <div class="content-box-content">
                <div class="tab-content default-tab" id="tab1">
                    <table>
                        <thead>
                        <tr>
                            <th><input class="check-all" type="checkbox" /></th>
                            <th>商品名称</th>
                            <th>商品图片</th>
                            <th>商品描述</th>
                            <th>商品价格</th>
                            <th>操作</th>
                        </tr>
                        </thead>
    
                        <tbody>
                            <tr th:each="good : ${goods}">
                                <td><input type="checkbox" /></td>
                                <td th:text="${good.gname}">Lorem ipsum dolor</td>
                                <!--默认展示商品的第一张图片-->
                                <td><img style=" 120px;height: 100px;" th:src="|http://192.168.59.131/${#strings.setSplit(good.gimage,'|')[0]}|"/></td>
                                <td th:text="${good.ginfo}">Consectetur adipiscing</td>
                                <td th:text="${#numbers.formatCurrency(good.gprice)}">Donec tortor diam</td>
                                <td>
                                    <!-- Icons --> <a href="#" title="Edit"><img
                                        src="resources/images/icons/pencil.png" alt="Edit" /></a> <a
                                        href="#" title="Delete"><img
                                        src="resources/images/icons/cross.png" alt="Delete" /></a> <a
                                        href="#" title="Edit Meta"><img
                                        src="resources/images/icons/hammer_screwdriver.png"
                                        alt="Edit Meta" /></a>
                                </td>
                            </tr>
                        </tbody>
    
                        <tfoot>
                        <tr>
                            <td colspan="6">
                                <div class="bulk-actions align-left">
                                    <a class="mybutton" href="/topage/goodsadd">添加商品</a>
                                </div>
                                <div class="clear"></div>
                            </td>
                        </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
            <!-- End .content-box-content -->
        </div>
    </div>
    <!-- End #main-content -->
    </body>
    </html>
    //ImgController
    
    import com.alibaba.fastjson.JSON;
    import com.github.tobato.fastdfs.domain.StorePath;
    import com.github.tobato.fastdfs.service.FastFileStorageClient;
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    
    @Controller
    @RequestMapping("/imgs")
    public class ImgController {
    
        @Autowired
        private FastFileStorageClient fastFileStorageClient;
        //private static final String UPLOAD_PATH = "e:\imgs";
    
        @RequestMapping("/uploader")
        @ResponseBody
        public String uploadImg(MultipartFile file) {
    
            //获得上传文件后辍的下标 xxx.png
            int index = file.getOriginalFilename().lastIndexOf(".");//返回指定字符在此字符串中最后一次出现处的索引
            String suffix =file.getOriginalFilename().substring(index+1);
            System.out.println("截取到的文件名后辍: "+suffix);
    //文件上到FastDFS try { StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), suffix, null); //获取上传到FastDFS中图片的路径 String imgUrl = storePath.getFullPath(); System.out.println("FastDFS中图片的路径: "+imgUrl); //将存FastDFS中图片的路径以JSON方式返回到前端页面 Map<String,Object> map = new HashMap<>(); map.put("imgUrl",imgUrl); String param = JSON.toJSONString(map); return param; //return "{"uploadPath":"" + imgUrl + ""}"; } catch (IOException e) { e.printStackTrace(); } /* //文件上传到本地磁盘 try ( InputStream inputStream = file.getInputStream(); OutputStream outputStream = new FileOutputStream(UPLOAD_PATH + UUID.randomUUID().toString()); ) { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { e.printStackTrace(); }*/ return null; } }
    //GoodsController 
    
    import com.alibaba.dubbo.config.annotation.Reference;
    import com.qf.entity.Goods;
    import com.qf.service.IGoodsService;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/goods")
    public class GoodsController {
    
        @Reference
        private IGoodsService goodsService;
        /**
         * 查询商品列表
         */
        @RequestMapping("/list")
        public String goodslist(ModelMap map){
            List<Goods> goods = goodsService.queryAll();
            map.put("goods",goods);
            return "goodslist";
        }
    
        /**
         * 新增商品
         */
        @RequestMapping("/insert")
        public String goodsinsert(Goods goods){
            int count = goodsService.insert(goods);
            return "redirect:/goods/list";
        }
    }
    //spring boot的入口启动类
    
    import com.github.tobato.fastdfs.FdfsClientConfig;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Import;
    
    @SpringBootApplication(scanBasePackages = "com.qf")
    @Import(FdfsClientConfig.class)
    public class ShopBackApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ShopBackApplication.class, args);
        }
    
    }
  • 相关阅读:
    Excel中删除含有空值的整行或是整列
    Power Pivot(二)
    Power Pivot(一)
    携程数据清洗
    Matplotlib基础绘图
    Pandas 数据清洗常见方法
    天猫美妆数据清洗步骤概括
    淘宝美妆双十一数据可视化(下)
    淘宝美妆双十一数据清洗(上)
    乐高天猫旗舰店数据分析
  • 原文地址:https://www.cnblogs.com/wakey/p/10686951.html
Copyright © 2020-2023  润新知