話不多說上代碼
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("文件上傳") } } }) })
控制層代碼:思路(將上傳的文件存儲在本地的盤符,但是當要將本地文件如何映射到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
//springboot 5.0 addResourceLocations 類已經棄用 ,可以使用WebMvcConfigurationSupport
public class WebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
//其實這里addResourceHandler是映射的一個請求,完全可以不用映射在static目錄下, 可以理解為一個@RequestMapping,只不過這個請求是映射到本地的靜態資源而已
registry.addResourceHandler("/static/probimg/**").addResourceLocations("file:E://upload/");
}
}
這個文件不需要放東西,然后重啟服務器,在瀏覽器下輸入該目錄會顯示本地的文件