idea图片上传

图片上传
Jsp页面代码:
<%–头像上传文本框–%>

图片

Script代码
//图片上传部分
//双击图片弹出文件选择框
$("#userPicture").dblclick(function () {
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲upPortrait").cl…/i;
var imgReader = new FileReader();

//文件读取器读取到文件后的回调事件
imgReader.onload = function (event) {
//显示图片 base64编码的图片
$("#userPicture").attr(“src”, event.target.result);
}

$("#upPortrait").change(function () {
//获取出文件选择器中的第一个文件
var file = $("#upPortrait").get(0).files[0];
//判断文件选择类型
if (regexImageFilter.test(file.type)) {
//读取文件转换成URL把图片转为Base64编码
imgReader.readAsDataURL(file);
} else {
layer.alert(“请选择图片”);
}
});
修改中如何显示图片:
//显示图片
if (jsonMsg.data.picture != undefined && jsonMsg.data.picture != null && jsonMsg.data.picture != “”) {
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲userPicture").p…{ctx}/commodity?method=getPortraitImage&imgName=’ + jsonMsg.data.picture);
}
表单提交用:
var upFormData = new FormData();

for (var x in fromData.field) {
//append(名称,值)
upFormData.append(x, fromData.field[x])
}
//把文件添加到upFormData
var file = $("#upPortrait").get(0).files[0];
upFormData.append(“portrait”, file);

// 提交表单
var layerIndex = layer.load();//不传参,默认为0;
$.ajax({
type: “POST”,//文件上传 只能是post
url: url,
data: upFormData,
cache: false,
processData: false,//禁止jquery对上传的数据进行处理
contentType: false,
dataType: ‘json’,
success: function (jsonMsg) {
layer.close(layerIndex);
if (jsonMsg.state) {
layer.msg(jsonMsg.msg, {icon: 6});
layer.close(layerFormIndex);//关闭弹窗
table.reload(‘tablePosition’, {});//表格的重载
} else {
layer.msg(jsonMsg.msg, {icon: 5});
}
;
}
});
return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
});
Servie层
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 10; // 10MB 内存临界值 - 超过后将产生临时文件并存储于临时目录中
private static final int MAX_FILE_SIZE = 1024 * 1024 * 30; // 30MB 最大文件大小
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 40; // 40MB 最大请求大小
private static final String UPLOAD_PATH = “/E:/smProjects/sm_admin/commodity/”;//图片上传目录

/**

  • 根据图片名返回图片 流
    */
    public void getPortraitImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取参数
    String imgName = request.getParameter(“imgName”);
    if (Tools.isNotNull(imgName)) {
    //图片名不未空
    String imgPath = UPLOAD_PATH + imgName;
    File fileImg = new File(imgPath);
    if (fileImg.exists()) {
    //指定返的类型
    response.setContentType(Tools.getImageContentType(imgName));

         InputStream in = null;
         OutputStream out = null;
         try {
             in = new FileInputStream(fileImg);
             out = response.getOutputStream();
            
             IOUtils.copy(in, out);
             out.flush();
         } finally {
             if (in != null) in.close();
             if (out != null) out.close();
         }
     }
    

    }
    }

/**

  • 新增
    */
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JsonMsg jsonMsg = new JsonMsg();
    //判断表单是否是文件上传的表单
    if (!ServletFileUpload.isMultipartContent(request)) {
    // 如果不是则停止
    jsonMsg.setMsg(“Error: 表单必须包含 enctype=multipart/form-data”);
    returnJson(response, jsonMsg);
    }
    SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyyMMdd_HHmmssSSS_”);

    //配置上传相关的参数
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //设置存临界值 - 超过后将产生临时文件并存储于临时目录中
    factory.setSizeThreshold(MEMORY_THRESHOLD);

    //设置临时存储目录
    factory.setRepository(new File(System.getProperty(“java.io.tmpdir”)));
    ServletFileUpload upload = new ServletFileUpload(factory);
    //设置文件最大值 30M
    upload.setFileSizeMax(MAX_FILE_SIZE);
    //设置请求的大小最大值
    upload.setSizeMax(MAX_REQUEST_SIZE);

    //中文编码
    upload.setHeaderEncoding(“UTF-8”);

    //判断文件存放目录是否存在
    File uploadDir = new File(UPLOAD_PATH);
    if (!uploadDir.exists()) {
    uploadDir.mkdirs();
    }

    SysCommodity saveUser = new SysCommodity();
    //解析请求内容,提前文件 和 普通参数
    try {
    List fileItems = upload.parseRequest(request);

     if (fileItems != null && fileItems.size() > 0) {
         //遍历
         for (FileItem item : fileItems) {
             //获取自动名称 -- 参数名request.getParameter("")
             String fieldName = item.getFieldName();
             //判断是文件 还是普通字段
             if (!item.isFormField()) {
                 //不是表单元素  文件
                 if ("portrait".equals(fieldName)) {//判断是否是头像文件
                     //拼接文件名  item.getName()--》文件名
                     String fileName = dateFormat.format(new Date()) + System.nanoTime() + Tools.getFileExt(item.getName());
                     //存放路径
                     String filePath = UPLOAD_PATH + fileName;
                     File saveFile = new File(filePath);
                     System.err.println(filePath);
                     //保存文件到硬盘
                     item.write(saveFile);
                     //把文件名保存到需要新增的对象中
                     saveUser.setPicture(fileName);
                 }
             } else {
                 // 表单元素
                 //需要通过流去读取
                 BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream(), StandardCharsets.UTF_8));
                 String strValue = br.readLine();//读取到值
                 if (fieldName == null) continue;
                 switch (fieldName) {
                     case "commodityBarcode": //条形码
                         saveUser.setCommodityBarcode(strValue);
                         break;
                     case "lowestPrice": //最低售价
                         saveUser.setLowestPrice(strValue);
                         break;
                     case "referencePrite": //参考进货价
                         saveUser.setReferencePrite(strValue);
                         break;
                     case "commodityNumber1": //商品编号
                         saveUser.setCommodityNumber(strValue);
                         break;
                     case "commodityName": //角色id
                         if (Tools.isNotNull(strValue)) {
                             saveUser.setCommodityName(strValue);
                         } else {
                             throw new RuntimeException("请填写商品名称!");
                         }
                         break;
                     case "commodityStatusId": //商品类型
                         if (Tools.isNotNull(strValue)) {
                             saveUser.setCommodityClassId(strValue);
                         } else {
                             throw new RuntimeException("请选择商品类型!");
                         }
                         break;
                     case "commodityUnit": //商品单位
                         saveUser.setCommodityUnit(strValue);
                         break;
                     case "commodityWeight": //商品重量
                         saveUser.setCommodityWeight(strValue);
                         break;
                     case "costPrite": //成本价
                         saveUser.setCostPite(strValue);
                         break;
                     case "commodityPrice": //零售价
                         saveUser.setCommodityPrice(strValue);
                         break;
                     case "topClassify": //仓库
                         saveUser.setEntrepotId(strValue);
                         break;
                     case "entrepotAmount": //初期库存数
                         saveUser.setCommodityQuantity(Integer.parseInt(strValue));
                         break;
                     case "remark": //备注
                         saveUser.setRemark(strValue);
                         break;
                 }
             }
         }
         boolean isOk = this.commodityService.insert(saveUser);
         if (isOk) {
             jsonMsg.setState(true);
             jsonMsg.setMsg("新增成功");
         } else {
             jsonMsg.setMsg("新增失败");
         }
     } else {
         jsonMsg.setMsg("参数异常");
     }
    

    } catch (FileUploadBase.SizeLimitExceededException e) {
    e.printStackTrace();
    jsonMsg.setMsg(“您上传文件超过了上传文件” + MAX_FILE_SIZE + “M 的限制”);
    } catch (FileUploadException e) {
    e.printStackTrace();
    jsonMsg.setMsg(“文件上传失败”);
    } catch (RuntimeException e) {
    e.printStackTrace();
    //数据校验失败的异常信息
    jsonMsg.setMsg(e.getMessage());
    } catch (Exception e) {
    e.printStackTrace();
    jsonMsg.setMsg(“表单提交失败”);
    }

    returnJson(response, jsonMsg);
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
将图片路径存入 MySQL 数据库可以按照以下步骤进行: 1. 创建一个包含图片路径的表,可以包含以下列:`id`(自增主键),`image_path`(存储图片路径的列),`created_at`(创建时间),`updated_at`(更新时间)等。 2. 在 PHP 代码中,使用 `move_uploaded_file()` 函数将上传的图片保存到服务器上的指定目录中。例如: ``` $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["image"]["name"]); move_uploaded_file($_FILES["image"]["tmp_name"], $target_file); ``` 3. 将保存在 `$target_file` 变量中的图片路径插入到 MySQL 数据库中。可以使用 `mysqli_query()` 函数执行 `INSERT INTO` 语句。例如: ``` $link = mysqli_connect("localhost", "username", "password", "database"); $image_path = mysqli_real_escape_string($link, $target_file); $query = "INSERT INTO images (image_path) VALUES ('$image_path')"; mysqli_query($link, $query); ``` 其中,`mysqli_real_escape_string()` 函数可以确保插入的路径字符串不会破坏 MySQL 查询语句的语法结构。 4. 当需要在网页中显示图片时,从数据库中查询图片路径,并将其作为 `<img>` 标签的 `src` 属性的值。例如: ``` $query = "SELECT image_path FROM images WHERE id = 1"; $result = mysqli_query($link, $query); $row = mysqli_fetch_assoc($result); $image_path = $row["image_path"]; echo "<img src='$image_path' />"; ``` 这样,用户就可以在网页上看到存储在数据库中的图片了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值