springboot⽂件上传步骤,详细,ajax⽂件上传,formdata封装话不多说上代码
jsp页⾯:
<form id="addForm" 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("⽂件上传")
}inputtypefile不上传文件
}
})
})
控制层代码:思路(将上传的⽂件存储在本地的盘符,但是当要将本地⽂件如何映射到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()+ OriginalFilename();
if(!pPicture.isEmpty()){
byte [] bytes = Bytes();
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 t.annotation.Configuration;
import org.springframework.fig.annotation.ResourceHandlerRegistry;
import org.springframework.fig.annotation.WebMvcConfigurerAdapter;
@Configuration
//springboot 5.0 addResourceLocations 类已经弃⽤ ,可以使⽤
public class WebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //其实这⾥addResourceHandler是映射的⼀个请求,完全可以不⽤映射在static⽬录下, 可以理解为⼀个@RequestMapping,只不过这个请求是映射到本地的静态资源⽽已        registry.addResourceHandler("/static/probimg/**").addResourceLocations("file:E://upload/");
}
}
这个⽂件不需要放东西,然后重启服务器,在浏览器下输⼊该⽬录会显⽰本地的⽂件

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。