java上传图片到服务器下

应用场景

在我们项目中总是会有修改头像,或者是在添加记录时需要添加图片作为描述的功能,这样我们就需要将图片保存在服务器中,我写了一个测试的小功能,我在本地启动了一个tomcat作为模拟服务器将需要上传的图片保存在了tomcat的指定目录下,现在分享出来希望能帮助到大家-.-

代码实现

HTML、我是在添加商品的时候上传文件到服务器下

<div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-product-add" action="/product/add/image" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label class="col-sm-3 control-label">商品名称:</label>
                <div class="col-sm-8">
                    <input name="pname" id="pname" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">商品价格:</label>
                <div class="col-sm-8">
                    <input name="price" id="price" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">商品图片:</label>
                <div class="col-sm-8">
                    <input id="file" name="file" class="form-control" multiple="multiple" type="file">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">热门级别:</label>
                <div class="col-sm-8">
                    <input name="isHot" id="isHot" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">商品详情:</label>
                <div class="col-sm-8">
                    <input name="pdesc" id="pdesc" class="form-control" type="text" required>
                </div>
            </div>
        </form>
    </div>

JS、提交表单信息并且将文件传输到后端

	function submitHandler() {
            if ($.validate.form()) {
                var image = $('#file')[0].files[0];
                if (image == null) {
                    $.modal.alertError("请先选择文件路径");
                }else if(image.type!="image/jpg"&&image.type!="image/gif"&&image.type!="image/jpeg"&&image.type!="image/png"){
                    $.modal.alertError("您上传图片的类型不符合(.jpg|.jpeg|.gif|.png)!");
                }else{
                    // ajax提交
                        var pname = $("input[name='pname']").val();
                        var pdesc = $("input[name='pdesc']").val();
                        var isHot = $("input[id='isHot']").val();
                        var price = $("input[name='price']").val();
                        var formdata = new FormData();
                        formdata.append('image', $('#file').get(0).files[0]);
                        formdata.append('pname', pname);
                        formdata.append('pdesc', pdesc);
                        formdata.append('isHot', isHot);
                        formdata.append('price', price);
                        $.ajax({
                            type:'post',
                            contentType: false,
                            processData: false,
                            cache : true,
                            url:ctx + 'product/add/image',
                            data:formdata,
                            success:function (data) {
                                $.operate.successCallback(data);
                            }
                        })
                }
            }
        }

Controller、接收商品信息和MultipartFile 类型的文件

	/**
       * @Author: Mr.fzz
       * @Description: 新增保存商品详情
       * @Date: 12:27 2021/3/7
       * @Param file(图片)、manageProduct(商品实体类)
       * @return AjaxResult
       **/
    @RequiresPermissions("product:add")
    @Log(title = "商品详情", businessType = BusinessType.INSERT)
    @PostMapping("/add/image")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("image") MultipartFile file,ManageProduct manageProduct){
        // 将文件的名称封装进实体类
        manageProduct.setPimage(file.getOriginalFilename());
        // 将MultipartFile文件下载到tomcat的指定目录下
        AddImageUploadUtils addImageUploadUtils = new AddImageUploadUtils();
        // 添加商品信息到数据库
        String upload = addImageUploadUtils.upload(file, manageProduct.getPimage());
        if (upload=="文件已经存在"){
            return error("文件已经存在");
        }
        return toAjax(manageProductService.insertManageProduct(manageProduct));
	}

AddImageUploadUtils 、上传文件的工具类把图片放到指定的URL路径下

public class AddImageUploadUtils {

    private String serverPath = "http://192.168.188.118:8084/upload/";// tomcat地址

	/*
      * @Author: Mr.fzz
      * @Description: 上传图片到tomcat
      * @Date: 17:46 2021/3/2
      * @Param MultipartFile 要上传的文件,imageName上传的文件名
      * @return 上传状态
      **/
    public String upload(MultipartFile file,String imageName){
        Client client = new Client();
        // 另一台tomcat的URL(真实路径)
        String realPath = serverPath + imageName;
        try {
            URL urlObj = new URL(realPath);
            HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
            oc.setUseCaches(false);
            oc.setConnectTimeout(3000); // 设置超时时间
            int status = oc.getResponseCode();// 请求状态
            if (200 == status) {
                // 200是请求地址顺利连通。。
                return "文件已经存在";
            }
            // 设置请求路径
            WebResource resource = client.resource(realPath);
            // 发送开始post get put(基于put提交)
            try {
                resource.put(String.class, file.getBytes());
                return realPath;
            } catch (IOException e) {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Product.html、通过指定路径+数据库保存的图片名称回显图片(具体在js中的商品图片字段)

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('商品详情列表')" />
</head>
<body class="gray-bg">
     <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="formId">
                    <div class="select-list">
                        <ul>
                            <li>
                                <label>主键:</label>
                                <input type="text" name="pid"/>
                            </li>
                            <li>
                                <label>商品名称:</label>
                                <input type="text" name="pname"/>
                            </li>
                            <li>
                                <label>商品价格:</label>
                                <input type="text" name="price"/>
                            </li>
                            <li>
                                <label>商品图片:</label>
                                <input type="text" name="pimage"/>
                            </li>
                            <li>
                                <label>商品详情:</label>
                                <input type="text" name="pdesc"/>
                            </li>
                            <li>
                                <label>更新时间:</label>
                                <input type="text" class="time-input" placeholder="请选择更新时间" name="updateTime"/>
                            </li>
                            <li>
                                <label>更新人:</label>
                                <input type="text" name="updatePerson"/>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="product:product:add">
                    <i class="fa fa-plus"></i> 添加
                </a>
                <a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="product:product:edit">
                    <i class="fa fa-edit"></i> 修改
                </a>
                <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="product:product:remove">
                    <i class="fa fa-remove"></i> 删除
                </a>
                <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="product:product:export">
                    <i class="fa fa-download"></i> 导出
                </a>
            </div>
            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        var editFlag = [[${@permission.hasPermi('product:edit')}]];
        var removeFlag = [[${@permission.hasPermi('product:remove')}]];
        var displayImage = [[${@permission.hasPermi('product:display')}]];
        var prefix = ctx + "product";

        $(function() {
            var options = {
                url: prefix + "/list",
                createUrl: prefix + "/add",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
                displayUrl: prefix + "/display/{id}",
                headerStyle: headerStyle,// 格式化表格
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                detailView: true,
                detailFormatter: detailFormatter,// 添加表格详情
                modalName: "商品详情",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'pid',
                    align: 'center',
                    title: '主键',
                    visible: false
                },
                {
                    field: 'pname',
                    align: 'center',
                    width:"200px",
                    title: '商品名称'
                },
                {
                    field: 'price',
                    align: 'center',
                    title: '商品价格'
                },
                {
                    field: 'pimage',
                    align: 'center',
                    title: '商品图片',
                    formatter: function (value, row, index) {
                        return '<img src="http://192.168.188.118:8084/upload/' + value + '" style="border-radius: 50%;overflow: hidden;width: 100px;">';
                    }
                },
                {
                    field: 'pdesc',
                    align: 'center',
                    title: '商品详情'
                },
                {
                    field: 'updateTime',
                    width:"170px",
                    align: 'center',
                    title: '更新时间'
                },
                {
                    field: 'updatePerson',
                    align: 'center',
                    title: '更新人'
                },
                {
                    title: '操作',
                    align: 'center',
                    width: "150px",
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" οnclick="$.operate.edit(\'' + row.pid + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" οnclick="$.operate.remove(\'' + row.pid + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
        });
        function headerStyle(column) {
            return {
                pimage: {
                    css: { color: 'red' }
                }
            } [column.field]
        }

        function detailFormatter(index, row) {
            var html = [];
            $.each(row, function(key, value) {
                html.push('<p><b>' + key + ':</b> ' + value + '</p>');
            });
            return html.join('');
        }
    </script>
</body>
</html>

在这里插入图片描述

梦想也许在今天无法实现,但重要的是,它在你心里。重要的是,你一直在努力,加油!!!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值