上传图片(文件)

上传图片(文件)方式

一、通过文件方式上传

1. 单独一个图片或文件代码案例

1.1 配置文件上传解析器
<!--配置文件上传解析器 id必须为CommonsMultipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <!--支持的最大的上传文件大小 单位是:byte  10MB = 10*1024*1024-->
        <property name="maxUploadSize" value="10000000"></property>
    </bean>
1.2 编写前端页面(当前用jsp的表单提交)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--如果表单需要支持文件上传,需要添加enctype="multipart/form-data"--%>
<form action="upload" method="post" enctype="multipart/form-data">
    文件:<input type="file" name="file">
    <input type="submit" value="提交">
</form>
</body>
</html>
1.3 编写Controller层
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 * @create 2019/05/10
 */
@Controller
public class UploadController {

    private static final String UPLOAD_BASE_PATH = "C:\\upload\\";//定义图片上传根路径
    private static final String IMAGE_BASE_URL = "http://localhost:8080/file/";//定义图片访问根路径
    /*
    * MultipartFile file 用于绑定前台传过来文件对象 file 形参名 必须与前台表单中的name属性一致
    * */
    @RequestMapping("/upload")
    public String upload(MultipartFile file){
        //获取唯一的标识符作为文件名
        String fileName = UUID.randomUUID().toString();

        //获取文件原始文件名
        //System.out.println(file.getOriginalFilename());//a.b.jpg
        String originalFileName = file.getOriginalFilename();

        //拼接上传文件名
        fileName = fileName + originalFileName.substring(originalFileName.lastIndexOf("."));

        String uploadPath = UPLOAD_BASE_PATH+fileName;
        System.out.println("上传路径:"+uploadPath);

        try {
            //执行上传操作即可
            file.transferTo(new File(uploadPath));
            //将图片路径保存至数据库 http://localhost:8086/pic/c88ba14e-2a4b-4a8c-8516-63bb0f7b8b94.jpg
            String imageUrl = IMAGE_BASE_URL+fileName;//保存数据库
            //将路径存储到数据库中即可
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

}

如果要在前端显示图片需要在tomcat中配置路径
在tomcat中的server中Engine标签中的Host标签中添加如下代码

<Context docBase="C:/upload/file" path="/file" reloadable="true"/>

2 表单提交多个图片和其他多个数据同时提交案例

2.1 配置文件上传解析器(同上)
2.2 前端表单提交页面(当前用html语言和layui框架)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引用layui的样式-->
    <link rel="stylesheet" type="text/css" href="layui/css/layui.css">
</head>
<body>
<form class="layui-form" action="" lay-filter="addExtension" id="addExtension" enctype="multipart/form-data">
    <div class="layui-form-item">
        <label class="layui-form-label">商品主图片:</label>
        <div class="layui-input-inline">
            <input type="file" name="googsPicture" id="googsPicture" >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品名称:</label>
        <div class="layui-input-inline">
            <input type="text" name="goodsName" id="goodsName" required lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品价格:</label>
        <div class="layui-input-inline">
            <input type="text" name="goodsPrice" id="goodsPrice" required lay-verify="required" placeholder="请输入商品价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">商品描述</label>
        <div class="layui-input-block">
            <textarea name="goodsDescribe" placeholder="请输入内容" id="goodsDescribe" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品运费:</label>
        <div class="layui-input-inline">
            <input type="text" name="freight" id="freight" required lay-verify="required" placeholder="请输入运费" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品图片1:</label>
        <div class="layui-input-inline">
            <input type="file" name="pictureOne" id="pictureOne" >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品图片2:</label>
        <div class="layui-input-inline">
            <input type="file" name="pictureTwo" id="pictureTwo" >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品图片3:</label>
        <div class="layui-input-inline">
            <input type="file" name="pictureThree" id="pictureThree" >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品图片4:</label>
        <div class="layui-input-inline">
            <input type="file" name="pictureFour" id="pictureFour" >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">兑换门槛:</label>
        <div class="layui-input-inline">
            <input type="text" name="threshold" id="threshold" required lay-verify="required" placeholder="请输入天数" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">添加</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
</body>

<!--引用layui脚本-->
<script type="text/javascript" src="layui/layui.js"></script>

<script type="text/javascript">
    layui.use(['table','form','jquery'], function(){
    	var table = layui.table;
        var form = layui.form;
        var $ = layui.$;
        /*监听查询表单的提交事件*/
        form.on('submit(addExtension)', function(data){
            var formData  =  new FormData(document.getElementById("addExtension"));
			$.ajax({
				url: "addGoods.do",
				type: 'POST',
				data: formData,
		        async:false,
		        contentType: false,
		        processData: false,
		    	dataType: 'json',
				success: function(result){
					var a = result.code;
					if (a == 100) {
						alert("添加成功");
						parent.location.reload();
					}else{
						alert("添加失败");
					}
				}
			});
        }); 
    });
</script>
</html>
2.3 编写Controller层
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sm.dto.LayUITableData;
import com.sm.model.Goods;
import com.sm.service.GoodsService;
import com.sm.util.CommonUtil;
import com.sm.util.Msg;

@Controller
public class GoodsController {
	
	@Autowired
	private GoodsService goodsService;

	/**
	 *	添加商品
	 * @param googsPicture		主图片
	 * @param goodsName			商品名
	 * @param goodsPrice		商品价格
	 * @param goodsDescribe		商品描述
	 * @param freight			商品运费
	 * @param pictureOne		图片1
	 * @param pictureTwo		图片2
	 * @param pictureThree		图片3
	 * @param pictureFour		图片4
	 * @param threshold			兑换天数
	 * @return
	 */
	@RequestMapping("/addGoods")
	@ResponseBody
	public Msg addGoods(@RequestParam("googsPicture")MultipartFile googsPicture/*主图片*/
						,@RequestParam("goodsName")String goodsName/*商品名*/
						,@RequestParam("goodsPrice")String goodsPrice/*商品价格*/
						,@RequestParam("goodsDescribe")String goodsDescribe/*商品描述*/
						,@RequestParam("freight")String freight/*商品运费*/
						,@RequestParam("pictureOne")MultipartFile pictureOne/*图片1*/
						,@RequestParam("pictureTwo")MultipartFile pictureTwo/*图片2*/
						,@RequestParam("pictureThree")MultipartFile pictureThree/*图片3*/
						,@RequestParam("pictureFour")MultipartFile pictureFour/*图片4*/
						,@RequestParam("threshold")String threshold/*兑换天数*/
						) {
		
		if(googsPicture == null || pictureOne == null || pictureTwo == null || pictureThree == null || pictureFour == null) {
			return Msg.fail().add("msg", "添加失败");
		}
		
		Goods goods = new Goods();
		goods.setGoodsName(goodsName);//设置商品名
		goods.setGoodsPrice(Double.parseDouble(goodsPrice));//设置商品价格
		goods.setGoodsDescribe(goodsDescribe);//设置商品描述
		goods.setFreight(Double.parseDouble(freight));//设置运费
		goods.setThreshold(Integer.parseInt(threshold));//设置天数
		
		String path = null;
		try {
			//生成图片路径根据自己需求自己定义。当前用的工具类
			path = CommonUtil.saveFile(googsPicture);
			goods.setGoogsPicture(path);
		} catch (IllegalStateException e) {
			return Msg.fail().add("msg", "图片上传失败");
		} catch (IOException e) {
			return Msg.fail().add("msg", "图片上传失败");
		}
		try {
			path = CommonUtil.saveFile(pictureOne);
			goods.setPictureOne(path);
		} catch (IllegalStateException e) {
			return Msg.fail().add("msg", "图片上传失败");
		} catch (IOException e) {
			return Msg.fail().add("msg", "图片上传失败");
		}
		try {
			path = CommonUtil.saveFile(pictureTwo);
			goods.setPictureTwo(path);
		} catch (IllegalStateException e) {
			return Msg.fail().add("msg", "图片上传失败");
		} catch (IOException e) {
			return Msg.fail().add("msg", "图片上传失败");
		}
		try {
			path = CommonUtil.saveFile(pictureThree);
			goods.setPictureThree(path);
		} catch (IllegalStateException e) {
			return Msg.fail().add("msg", "图片上传失败");
		} catch (IOException e) {
			return Msg.fail().add("msg", "图片上传失败");
		}
		try {
			path = CommonUtil.saveFile(pictureFour);
			goods.setPictureFour(path);
		} catch (IllegalStateException e) {
			return Msg.fail().add("msg", "图片上传失败");
		} catch (IOException e) {
			return Msg.fail().add("msg", "图片上传失败");
		}
		
		System.out.println("goods===="+goods);
//		插入商品对象。到数据库中
		int i = goodsService.insert(goods);
		
		if(i == 1) {
			return Msg.success().add("msg", "添加成功");
		}else {
			return Msg.fail().add("msg", "添加失败");
		}
	}
}

service和dao和实体类省略。
可能用到一些工具类。都是自己定义的工具类。根据自己需求自己编写。

二单个文件上传

前端js
		layer.open({
          title: '上传审批凭证',
          skin: 'layui-layer-rim',
          area: ['350px', 'auto'],
          content: '<div class="input-group">'
                  + '<input id="fileId" type="file" name="file" value="上传附件">'
                  + '</div>'
          ,
          btn: ['确定', '不需要凭证'],
          btn1: function (index, layero) {
              let file = document.getElementById('fileId').files[0];//获取文件流
              let formData = new FormData();
              formData.append('file', file);
              // 上传文件
              $.ajax({
                  url: baseURL + "api/lcverifier/uploadImgs",
                  type: 'post',
                  data: formData,
                  processData: false,
                  contentType: false,
                  success: function (response) {
                      if (response.code == 0) {
                          alert("上传成功");
                      } else {
                          alert("上传失败");
                      }
                  }
              });
          },
          btn2: function (index,layero) {
              layer.close(index);
          }
      });
controller(返回的是文件名。可以根据自己的需求进行存储到数据库和返回的数据。)
	/**
     * 文件上传
     */
    @PostMapping("/uploadImgs")
    @ApiOperation(value = "单个文件上传", notes = "单个文件上传")
    public R uploadImgs(@RequestParam("file") MultipartFile file) {
        String path = fileUtils.uploadFile(file);
        return R.ok(path);
    }
返回的参数工具类
/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.lcwing.common.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午9:59:27
 */
public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	
	public R() {
		put("code", 0);
		put("msg", "success");
	}
	
	public static R error() {
		return error(500, "未知异常,请联系管理员");
	}
	
	public static R error(String msg) {
		return error(500, msg);
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put("msg", msg);
		return r;
	}
	
	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	@Override
	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}
}

上传文件工具类
public String uploadFile(MultipartFile file) {
        String imgPath = getUploadPath();//获取文件存储的路径
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fileExt;
        try {
            File dirFile = new File(imgPath + fileName);
            file.transferTo(dirFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
获取文件存储的服务器路径
	private static String USER_HOME = System.getProperties().getProperty("user.home") + File.separator;

    public static String getUploadPath() {
        String path = USER_HOME + "urban" + File.separator;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值