java圖片和文本同時(shí)提交到表單的實(shí)例代碼
首先來看如下效果圖片:

表單代碼:
<form action="/addPro" method="post" enctype="multipart/form-data">
<a>寵物(或產(chǎn)品)類型:</a><select id="categoryID" name="cid"></select><br/><br/>
<a>寵物(或產(chǎn)品)名字:</a><input type="text" name="cname"><br/><br/>
<a>一句話介紹:</a><input type="text" name="introduction"><br/><br/>
<a>題目:</a><input type="text" name="title"><br/><br/>
<a>價(jià)錢:</a><input type="text" name="price"><br/><br/>
<a>庫存:</a><input type="text" name="stock"><br/><br/>
<a>狀態(tài):</a><select name="status">
<option value="1">在售</option>
<option value="2">下架</option>
<option value="3">刪除</option>
</select><br/><br/>
<a>頭像設(shè)置:</a><input type="file" οnchange="previewFile()" name="fileName">
<br/>
<img src="${data.image}" alt="Image preview"/><br/>
<a>詳細(xì)描述(編輯完需要在文本框右上角點(diǎn)保存):</a><br/>
<div id="editor">
<p>商品詳細(xì)描述</p>
<p>編輯完需要在文本框右上角點(diǎn)保存</p>
</div><input type="hidden" name="details" id="detail"><br/><br/>
<input type="submit" value="新增商品">
</form>
提交表單是采用二進(jìn)制方式提交,所以一般用來上傳圖片操作,當(dāng)在這個(gè)表單下同時(shí)上傳文本,就會(huì)報(bào)錯(cuò)。但是業(yè)務(wù)需要上傳商品是文本和圖片同時(shí)上傳的,所以這里要用到commons的四個(gè)包,使用Maven導(dǎo)入,如下:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io有關(guān)圖片文本同時(shí)上傳 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections --> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> </dependency>
Java代碼如下:
主要判斷每一個(gè)參數(shù)的屬性,圖片的則進(jìn)行圖片處理,文本則進(jìn)行文本處理。
//新增產(chǎn)品
@RequestMapping("/addPro")
public void addPro(HttpServletRequest request, HttpServletResponse response) throws IOException {
//編碼規(guī)范
response.setContentType("text/html");
// response.setCharacterEncoding("utf-8");
Product product = new Product();
//這種方法主要通過if (item.isFormField())這個(gè)條件判別文件還是非文件
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
} // 解析request請(qǐng)求
Iterator iter = items.iterator();// 遍歷表單中提交過來的內(nèi)容
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) { // 如果是表單域 ,就是非文件上傳元素
String value = item.getString("UTF-8"); // 獲取value屬性的值,這里需要指明UTF-8格式,否則出現(xiàn)中文亂碼問題
if (item.getFieldName().equals("cid")) {// 對(duì)應(yīng)form中屬性的名字
int categoryId = Integer.parseInt(value);
product.setCategory_id(categoryId);
} else if (item.getFieldName().equals("cname")) {
product.setName(value);
}else if (item.getFieldName().equals("introduction")) {
product.setIntroduction(value);
}else if (item.getFieldName().equals("title")) {
product.setTitle(value);
}else if (item.getFieldName().equals("price")) {
BigDecimal price=new BigDecimal(value);
product.setPrice(price);
}else if (item.getFieldName().equals("stock")) {
product.setStock(Integer.parseInt(value));
}else if (item.getFieldName().equals("status")) {
product.setStatus(Integer.parseInt(value));
}else if (item.getFieldName().equals("details")) {
product.setDetail(value);
}
}else {
String filename = item.getName(); // 文件的名字
String imgname = filename.substring(0, filename.indexOf(".")); //減去“.”后面的字符
//tomcat啟動(dòng)位置
// String t1 = System.getProperty("user.dir").substring(0,
// System.getProperty("user.dir").length() - 4);
String path = request.getServletContext().getRealPath("img"); //target找到img位置
Long time = Calendar.getInstance().getTimeInMillis(); //時(shí)間戳,保證文件命名不重復(fù)
String imgurl = "./img/"+imgname+time+".jpg";
product.setImage(imgurl);
System.out.println(imgurl);
File saveFile = new File(path+"/" + imgname+time+".jpg"); // 定義一個(gè)file指向一個(gè)具體的文件
try {
item.write(saveFile);// 把上傳的內(nèi)容寫到一個(gè)文件中
System.out.println("上傳到"+path+"成功");
} catch (Exception e) {
/* e.printStackTrace(); */
System.out.println("文件"+path+"為空");
}
}
}
if(productDaoService.addProduct(product)){
PrintWriter out = response.getWriter();
out.print("<script language=\"javascript\">alert('ADD SUCCESS');window.location.href='/admin/administrator'</script>");
}else {
PrintWriter out = response.getWriter();
out.print("<script language=\"javascript\">alert('增加失敗');window.location.href='/admin/addProduct'</script>");
}
}
以上就是java實(shí)現(xiàn)圖片和文本同時(shí)提交到表單的詳細(xì)內(nèi)容,感謝大家的學(xué)習(xí)和對(duì)腳本之家的支持。
相關(guān)文章
基于Java匯總Spock框架Mock靜態(tài)資源經(jīng)驗(yàn)
這篇文章主要介紹了基于Java匯總Spock框架Mock靜態(tài)資源經(jīng)驗(yàn),前面講了?Spock框架Mock對(duì)象、方法經(jīng)驗(yàn)總結(jié),今天分享一下Spock框架中Mock靜態(tài)資源的實(shí)踐經(jīng)驗(yàn)匯總。分成靜態(tài)資源和混合場(chǎng)景,需要的朋友可以參考一下2022-02-02
你肯定能看懂的Java IO相關(guān)知識(shí)總結(jié)
群里有大佬說想讓我寫一篇NIO,一直也沒寫,但是和同事聊天也說對(duì)Java的IO不是很清晰,因此今天就寫下Java的io,先打個(gè)基礎(chǔ),下次寫NIO,需要的朋友可以參考下2021-05-05
springboot內(nèi)置的tomcat支持最大的并發(fā)量問題
這篇文章主要介紹了springboot內(nèi)置的tomcat支持最大的并發(fā)量問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Springboot Maven打包跳過測(cè)試的五種方式小結(jié)
本文主要介紹了Springboot Maven打包跳過測(cè)試的五種方式小結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
MybatisPlus分頁查詢與多條件查詢介紹及查詢過程中空值問題的解決
mybatisplus是個(gè)很好用的插件,相信小伙伴們都知道,下面這篇文章主要給大家介紹了關(guān)于mybatis-plus實(shí)現(xiàn)分頁查詢與多條件查詢介紹及查詢過程中空值問題的相關(guān)資料,需要的朋友可以參考下2022-10-10

