Java实现图片上传到服务器

Java实现图片上传到服务器


#这几天研究图片上传到服务器并回显到页面遇到了问题,在这里总结一下!希望对各位有用!!!

先上代码

jsp代码:

<form id="myform" method="post" enctype="multipart/form-data">
                    <div class="form-group" >
                        <label for="plainGoodsName">商品名</label>
                        <input type="text" class="form-control" id="plainGoodsName" name="plainGoodsName" placeholder="请输入商品名">
                    </div>

                    <div class="form-group">
                        <label for="plainGoodsImg">商品图片</label>

                        <a style="float: left;border:1px solid #eee;width: 100%;padding: 10px;box-sizing: border-box;margin:5px 0;" href="javascript:;" class="a-upload">
                            <input type="file" name="files" id="plainGoodsImg" onchange="xmTanUploadImg_1(this,'xmTanImg_1')" accept="image/*"/>
                            <img style="width: 80px;" id="xmTanImg_1"/>
                            <div style="width: 80px;height: 80px;display: none;" id="xmTanDiv_1"></div>
                        </a>
                    </div>


                    <div class="form-group">
                        <label for="plainGoodsPrice">商品价格</label>
                        <input type="text" class="form-control" id="plainGoodsPrice" name="plainGoodsPrice" placeholder="请输入商品价格">
                    </div>

                    <div class="form-group">
                        <label for="plainGoodsNum">商品库存</label>
                        <input type="text" class="form-control" id="plainGoodsNum" name="plainGoodsNum" placeholder="商品库存">
                    </div>
                    <div class="form-group">
                        <label for="plainGoodsContext">商品描述</label>
                       <!-- <input type="text" class="form-control" id="plainGoodsContext" name="plainGoodsContext" placeholder="商品描述"> -->
                        <textarea class="form-control" id="plainGoodsContext" name="plainGoodsContext" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                                 <label></label>
                             <button type="button" onclick="saveGoods()" class="btn btn-primary">添加商品</button>
                    </div>
                </form>

问题

第一、上传图片时form表单中加入 enctype=“multipart/form-data” 否则会出现问题 后台接收不到
(jsp的id接收后台传过来的值 通过标签赋值 name是向后台传值用的 如果没有name没法传值==这是给我自己写的)

js代码

 var formData = new FormData($( "#myform" )[0]);
  $.ajax({
            url:"${ctx}/back/exchangeShopping/addGoods.action",
            type:"POST",
            dataType:"json",
            data:formData,
            processData: false,// 不加会报错
            contentType: false,// 不加会报错
            success:function(data) {
                if(data == "true"){
                    layer.msg('添加成功',{icon:6,time:1500,end:function () {
                            window.location.reload();
                        }});
                }else {
                    layer.msg(data,{icon:5,time:1500});
                }
            }
        })

有几个要注意的地方:
第一、ajax要加上两个属性
processData: false,// 不加会报错
contentType: false,// 不加会报错
第二、 var formData = new FormData($( “#myform” )[0]);
使用formdata序列化表单
关于jquery的 $(“form”).serialize()和 new FormData表单序列化
网址:https://blog.csdn.net/cracklibby/article/details/80013112
$(“form”).serialize()只会序列化表单不会序列化文件

问题:带文件上传的form表单序列化 传参问题
使用formdata 序列化form表单 后台使用@RequestParam(value = “files”, required = false)MultipartFile files,wFrontPlainGoods goods 接收
并且MultipartFile 名字要与页面name的名字相同

controller页面

@ResponseBody
	    @RequestMapping("/addGoods.action")
	    public String addGoods(@RequestParam(value = "files", required = false)MultipartFile files,wFrontPlainGoods goods){
	    	String Info = this.backExchangeShoppingService.addGoods(goods,files);
	        return JSONObject.toJSONString(Info);
	    }

后台 MultipartFile 接收文件 注意 名字要与页面起的名字一样(有些文章写的是名字一定不要一样 具体问题具体分析 我是小白不确定这个是为什么)
后面的对象时接收除文件以外的其他信息!

service页面:

//定义图片存储在服务器的路径
	public static final String PICTUREURL = "D:/nginx-1.13.8/html/slitLamp/screening/";
	public static final String CONFIGUREURL = "http://10.11.23.203:8029/";
	public String uploadPictureByFile(MultipartFile file) {
		// TODO 自动生成的方法存根
		String filename1 = "picture_" + UUID.randomUUID() + ".jpg";//生成唯一图片路径
		 if (!file.isEmpty()) {  
	            try {  
	                File filepath = new File(PICTUREURL);
	                if (!filepath.exists()) 
	                    filepath.mkdirs();
	                // 文件保存路径  
	               String savePath = PICTUREURL + filename1;  
	                // 转存文件  
	                file.transferTo(new File(savePath));  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  

				String url = CONFIGUREURL + filename1;
		return url;
	}

问题
第一、D:/nginx-1.13.8/html/slitLamp/screening/ 为图片存在nginx下的路径
http://10.11.23.203:8029/ 为nginx的IP+端口 通过这个可以访问启动nginx的页面
第二、配置nginx 在nginx下的conf文件夹下的nginx.conf文件中配置图片储存路径`
第三、程序的图片是下载到本地的 使用nginx挂载本地的图片 然后启动nginx服务后通过nginx的IP+端口+(有可能还要加)+图片名访问

    location ~ \.(gif|jpg|jpeg|png|bmp|swf)$              ###处理图片  
		{    
			root         D:/nginx-1.13.8/html/slitLamp/screening/;   ###对应的图片存入路径  
		}    

图片:![nginx配置图片](https://img-blog.csdnimg.cn/20190306091445409.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ExMTk0ODIxNTY4,size_16,color_FFFFFF,t_70)

关于nginx的问题

配置nginx的网址(Windows版 参考):
https://blog.csdn.net/y19910825/article/details/80301393
参考:
https://blog.csdn.net/qq_19244423/article/details/46877983
一台服务器挂载另一台服务器信息 参考:[Linux部署nginx挂载文件]
https://www.linuxidc.com/Linux/2013-07/87183.htm

当程序部署到服务器上时可以通过访问其他服务器来分担部署程序服务器的负载 以防止出现问题

以上链接是从网上复制过来的 如有问题请联系本人删除!!!

猜你喜欢

转载自blog.csdn.net/a1194821568/article/details/88211014