springmvc简单的文件上传+商品,自带UI。

/**
 * 添加商品
 * 通过流的方式上传文件
 *
 * @param
 * @return
 * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
 */
@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public String addProduct(@RequestParam("name") String name, @RequestParam("description") String description,
                         @RequestParam("price") double price, @RequestParam("stock") Integer stock,
                         @RequestParam("parentId") String parentId,
                         @RequestParam("fileName") MultipartFile file,
                         @RequestParam("desc") String desc) throws IOException {
    //分割value的值
    System.out.println(parentId);
    String[] p = parentId.split("-");
    int p1 = Integer.parseInt(p[0]);
    int p2 = Integer.parseInt(p[1]);
    int p3 = Integer.parseInt(p[2]);
    System.out.println(p1 + "" + p2 + "" + p3);
    System.out.println("打印文件描述信息" + desc);
    //jsp中上传的文件:file
    InputStream inputStream = file.getInputStream();//输入流IO
    //上传文件名
    String fileName = file.getOriginalFilename();
    OutputStream outputStream =
            new FileOutputStream("F:\\bdqn_Y2\\ssm1\\web\\images\\product\\" + fileName);
    byte[] bytes = new byte[1024];
    int length = -1;
    while ((length = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, length);
    }
    //关闭流
    outputStream.close();
    inputStream.close();
    //将file上传到服务器,硬盘中
    System.out.println("上传成功!");
    Product product = new Product();
    product.setCategoryLevel1Id(p1);
    product.setCategoryLevel2Id(p2);
    product.setCategoryLevel3Id(p3);
    product.setName(name);
    product.setDescription(description);
    product.setPrice(price);
    product.setStock(stock);
    product.setFileName(fileName);
    int num = productService.addProduct(product);
    System.out.println(num);
    if (num > 0) {
        return "redirect:index1.jsp";
    } else {
        return "/manage/product-add";
    }

}
  • UI
  • <tr>
        <td class="field">商品图片(*):</td>
        <td><input type="file" class="text" name="fileName"/>
            <br/>文件描述:<input type="text" name="desc"/>
            <span></span></td>
    </tr>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值