一、利用SpringMVC實現RESTful接口,獲取包括圖片在內的若干字段值。
RESTful接口的實現
`
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;node
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;web
import com.xx.persistence.Recommendation;
import com.xx.service.RecommendationService;ajax
@Controller
@RequestMapping(value = "/recommend")
public class RecommendController {spring
private final Log logger = LogFactory.getLog(RecommendController.class); @Autowired @Qualifier("recommendationService") RecommendationService recommendationService;//這裏只用來添加生成的Recommendation實例 @RequestMapping(value="/add-recommend",method=RequestMethod.POST,produces="application/json;charset=UTF-8") public @ResponseBody String addRecommend( @RequestParam (value="contentId")String contentId,//推薦的內容id @RequestParam ("type")String type,//推薦的內容類型 @RequestParam ("name") String name,//內容名稱 @RequestParam ("poster") MultipartFile poster,//內容海報(即上傳的圖片) @RequestParam ("description") String description,//描述 @RequestParam ("url") String url,//內容對應的url @RequestParam ("recommendDate") String recommendDateStr//推薦的時間 ){ System.out.println("begin to add recommendation:"); ObjectNode result = new ObjectMapper().createObjectNode(); if (type==null || name == null || poster ==null|| description ==null|| recommendDateStr == null || url == null) { return returnIllegalMsg(); } //獲取文件名 String fileName = poster.getOriginalFilename(); long currentTime = System.currentTimeMillis(); String path = type + File.separatorChar + contentId + File.separatorChar +currentTime + File.separatorChar + fileName; //圖片的uri路徑 String uriPath = filePath.getUriRoot() + path;//filePath.getUriRoot()能夠改成你須要的虛擬路徑 System.out.println("uriPath =" + uriPath); Date date = null; try { date = (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).parse(recommendDateStr); } catch (Exception e) { e.printStackTrace(); } Recommendation r = recommendationService.addRecommendation(new Recommendation(contentId, type, name, uriPath, description, url, date)); //圖片的存儲路徑 String dstFilePath = filePath.getRoot() + path;//filePath.getRoot()能夠改成你須要的存儲路徑 System.out.println("dstFilePath =" + dstFilePath); if(r!= null){ File picFile = new File(dstFilePath); if(!picFile.exists()){ if(!picFile.getParentFile().exists()){ picFile.getParentFile().mkdirs(); } try { //存儲文件 poster.transferTo(picFile); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //返回添加後的推薦條目id result.put("recommendId", r.getId()); return result.toString(); } return returnIllegalMsg(); } //返回參數錯誤的提示信息(json格式) private String returnIllegalMsg(){ ObjectNode result = new ObjectMapper().createObjectNode(); result.put("ret_code", 00001); result.put("ret_msg", "Illegal Parameters"); return result.toString(); }
}`apache
二、js發送post請求來模擬form表單提交。
爲了測試上述的接口,提供一個js提交post請求的例子
這是對應的divjson
<div id="div_addRecommendation"> <h1>添加熱門推薦</h1> <label>資源Id</label> <input type="text" name="add_contentId" id="add_contentId" class="txtfield" /> <label>類型</label><br/> <select id="add_type" > <option value="video" id="option_video">視頻</option> <option value="news" id="option_news">新聞</option> <option value="music" selected="selected">音樂</option> <option value="lottery">彩票</option> <option value="groupon">團購</option> <option value="game">遊戲</option> <option value="travel">旅遊</option> </select> <label>名稱</label> <input type="text" name="add_name" id="add_name" class="txtfield" /> <label >描述</label> <input type="text" name="add_description" id="add_description" class="txtfield" /> <label>連接</label> <input type="text" name="add_url" id="add_url" class="txtfield" /> <label >推薦時間</label> <input type="text" name="add_recommendDate" id="add_recommendDate" class="txtfield" /> <label >上傳圖片</label> <input id="f" type="file" name="f"/> <input type="button" name="add_recommend" id="add_recommend" class="flatbtn-blu hidemodal" value="添加"/>
js點擊添加,ajax發送post請求數組
$("#add_recommend").click(function(){ var contentId = $("#add_contentId").val(); var type = $("#add_type").val(); var name = $("#add_name").val(); var poster = document.getElementById("f").files[0]; var description = $("#add_description").val(); var url = $("#add_url").val(); var recommendDate = $("#add_recommendDate").val(); var request = location.protocol+"//"+location.host+"/xxx/recommend/add-recommend"; var data = new FormData(); data.append("contentId",contentId); data.append("type",type); data.append("name",name); data.append("poster",poster); data.append("description",description); data.append("url", url); data.append("recommendDate",recommendDate); $.ajax({ url: request, data: data, cache : false, processData : false, contentType : false, type: 'POST', timeout:3000, success: function(result){ alert("添加成功,recommendId爲"+result.recommendId); location.href = "${recommend}/recommend"; }, error:function(){ alert("reqeust error"); } });});
若是要實現上傳多張圖片的話,首先設置input標籤中的app
multiple="true/multiple/不寫屬性"
而後對應接口將MultipartFile類改成MultipartFile[]數組便可。ide
文章旨在記錄一下文件上傳的實現方式,若是有什麼不科學的地方,還須要你們批評指正。
因爲項目逐漸變大,將圖片和各個字段混合在一塊兒存儲不是一個好的方式,因而我將圖片存儲的服務獨立了出來,利用Jersey實現的RESTful接口,專一於操做圖片。 上班時間到啦,那麼下一篇再介紹利用Jersey與post請求是如何實現圖片上傳的。