话不多说上代码
jsp页面:
<form id="updateForm" enctype="multipart/form-data"> <input type="hidden" name="uId"> <div class="form-group"> <label class="control-label">商品名称:</label> <input type="text" name="pName" class="form-control"> </div> <div class="form-group"> <label class="control-label">库存:</label> <input type="text" name="pStock" class="form-control"> </div> <div class="form-group"> <label class="control-label">成本价:</label> <input type="text" name="pCost" class="form-control"> </div> <div class="form-group"> <label class="control-label">商品价格:</label> <input type="text" name="pPrice" class="form-control"> </div> <div class="form-group"> <label class="control-label">商品描述:</label> <input type="text" name="pDescription" class="form-control"> </div> <div class="form-group"> <label class="control-label">商品图片:</label> <img width="250" height="150" src=‘<c:url value="/static/probimg/222.png"></c:url>‘> <input type="file" name="pPicture" class="form-control"> </div> </form>
js代码:
$("#confirmAdd").click(function () { var formdata = new FormData($("#addForm")[0]); $.ajax({ type:"POST", dataType:"json", url:"addProduct", data:formdata, async:false, cache:false, contentType:false, processData:false, success:function(msg){ if(msg){ alert("文件上传") } } }) })
控制层代码:思路(将上传的文件存储在本地的盘符,但是当要将本地文件如何映射到jsp页面呢??)
@RequestMapping("addProduct") @ResponseBody public Boolean addProduct(HttpServletRequest request, String pName, Integer pStock, BigDecimal pCost, BigDecimal pPrice, String pDescription,@RequestParam("pPicture") MultipartFile pPicture) throws IOException { String fileName = UUID.randomUUID()+ pPicture.getOriginalFilename(); if(!pPicture.isEmpty()){ byte [] bytes = pPicture.getBytes(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("E:\\upload\\"+fileName))); bufferedOutputStream.write(bytes); bufferedOutputStream.close(); } Product product = new Product( null, pName, pStock, pCost, pPrice, pDescription, fileName); return productService.add(product); }
但是当要将本地文件如何映射到jsp页面呢??
package com.mall.han.utils; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/probimg/**").addResourceLocations("file:E://upload/"); } }
这个文件不需要放东西,然后重启服务器,在浏览器下输入该目录会显示本地的文件
原文地址:https://www.cnblogs.com/han-guang-xue/p/9988157.html
时间: 2024-10-10 07:42:40