SpringMVC之MultipartHttpServletRequest上傳圖片與其他表單資訊---初級
阿新 • • 發佈:2019-01-01
事先準備:
1、匯入相關jar包
2、在SpringMVC-servelt新增相關配置資訊(ps:這裡我使用的版本為Spring4.1.0)
如果預設條件:<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/>
開始:
前端頁面:
上面的程式碼僅僅作為參考,一定要加上enctype="multipart/form-data",不然controllers中只能拿到圖片的名字
後臺:
package ourmarket.controllers; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Timestamp; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import ourmarket.models.Goods; import ourmarket.models.ImageLibrary; import ourmarket.services.IGoodService; import ourmarket.services.IImageLibraryService; import sun.invoke.empty.Empty; @Controller public class GoodsPutaway { @RequestMapping("goodsPutaway") public String index(HttpServletRequest request, Model model, String goodsName, String goodsPrice, String goodsNum, String goodsDes, Short glocation) throws IllegalStateException, IOException { if ((goodsName == null) || (goodsDes == null) || (goodsNum == null) || (goodsPrice == null)) { return "goodsPutaway"; } if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; // 獲得第1張圖片(根據前臺的name名稱得到上傳的檔案) MultipartFile imgFile1 = multipartHttpServletRequest.getFile("Photo"); if (!imgFile1.isEmpty()) { //獲取前端傳來的檔名 String fileName = imgFile1.getOriginalFilename(); String SQLBasePath="goodsImg"; //拿到本地伺服器會話位置---可以是絕對地址 String realPath = request.getSession().getServletContext().getRealPath("/") + "\\"+SQLBasePath; Date date = new Date(); // 自定義的檔名稱---防止覆蓋以前 String trueFileName = date.getYear() + date.getMonth() + date.getDay() + date.getHours() + date.getMinutes() + fileName; // 設定存放圖片檔案的路徑 String path = realPath + trueFileName; try { //利用檔案流儲存檔案 imgFile1.transferTo(new File(path)); } catch (Exception e) { } } } return "shelvedGoods"; } }
作為基礎程式碼,我僅僅想給剛接觸這的朋友提供一個簡單的例子,幫助其快速的入門。
上邊程式碼我去掉了大部分其他資料庫程式碼 僅保留了關於儲存圖片方面的,我的程式碼也有漏洞及不合理地方,能給新朋友一點幫助我也很開心。
有什麼更好的建議請一定要提出來,萬分感謝!