使用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; width: 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; width: 500px; height: 120px; margin-bottom: 10px; padding: 20px;">
                                   <!-- <img src="xxx" style="height: 100px; width: 100px; margin-right: 5px;"/>
                                    <img src="xxx" style="height: 100px; width: 100px; margin-right: 5px;"/>
                                    <img src="xxx" style="height: 100px; width: 100px; margin-right: 5px;"/>
                                    <img src="xxx" style="height: 100px; width: 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="width: 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);
    }

}

 

posted on 2019-04-10 23:25 Ethon 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/wakey/p/10686951.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值