2

1、利用SpringMVC实现RESTful接口,获取包括图片在内的若干字段值。
RESTful接口的实现
`
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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;

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;

import com.xx.persistence.Recommendation;
import com.xx.service.RecommendationService;

@Controller
@RequestMapping(value = "/recommend")
public class RecommendController {

 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();
 }

}`

2、js发送post请求来模拟form表单提交。
为了测试上述的接口,提供一个js提交post请求的例子
这是对应的div

<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标签中的

multiple="true/multiple/不写属性"

然后对应接口将MultipartFile类改为MultipartFile[]数组即可。

文章旨在记录一下文件上传的实现方式,如果有什么不科学的地方,还需要大家批评指正。


由于项目逐渐变大,将图片和各个字段混合在一起存储不是一个好的方式,于是我将图片存储的服务独立了出来,利用Jersey实现的RESTful接口,专注于操作图片。
上班时间到啦,那么下一篇再介绍利用Jersey与post请求是如何实现图片上传的。


guodage
206 声望9 粉丝

永远不要害怕失败。


引用和评论

0 条评论