1.jsp页面
<td width="20%" class="pn-flabel pn-flabel-h"></td>
<td width="80%" class="pn-fcontent">
<img width="100" height="100" id="allImgUrl"/>
<input type="hidden" name="imgUrl" id="path"/>
<input type="file" onchange="uploadPic()" name="pic"/>
</td<script type="text/javascript"//上传function uploadPic(){
//定义参数
var options = {
url : "/upload/uploadPic.do",
dataType : "json",
type : "post",
success : function(data){
//回调 二个路径
//url
//path
$("#allImgUrl").attr("src",data.url);
$("#path").val(data.path);
}
}; //jquery.form使用方式 通常情况下,我们直接通过form提交的话,提交后当前页面跳转到form的action所指向的页面。然而,很多时候我们比不希望提交表单后页面跳转,
那么,我们就可以使用ajaxSubmit(obj)来提交数据。
$("#jvForm").ajaxSubmit(options);
}
</script>
2.修改springmvc.xml配置文件
在配置文件中添加如下代码:
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"> </property> <!-- 大小为1M 1*1024*1024 -->
</bean>
3.编写controller层
@Controller
public class UploadController {
//上传图片
@RequestMapping(value = "/upload/uploadPic.do")
public void uploadPic(@RequestParam(required = false) MultipartFile pic,HttpServletResponse response){
//扩展名
String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
//图片名称生成策略
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//图片名称一部分
String format = df.format(new Date());
//随机三位数
Random r = new Random();
// n 1000 0-999 99
for(int i=0 ; i<3 ;i++){
format += r.nextInt(10);
}
//实例化一个Jersey
Client client = new Client();
//保存数据库
String path = "upload/" + format + "." + ext;
//另一台服务器的请求路径是?
String url = Constants.IMAGE_URL + path;
//设置请求路径
WebResource resource = client.resource(url);
//发送开始 POST GET PUT
try {
resource.put(String.class, pic.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//返回二个路径
JSONObject jo = new JSONObject();
jo.put("url", url);
jo.put("path",path);
ResponseUtils.renderJson(response, jo.toString());
}
}
4.编写ResponseUtils工具类,用来异步发送
public class ResponUtils {
public static void render(HttpServletResponse response,String contentType,String text){
response.setContentType(contentType);
try {
response.getWriter().write(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//发送的是Json
public static void renderJson(HttpServletResponse response,String text){
render(response,"application/json;charset=UTF-8",text);
}
//发送xml
public static void renderXml(HttpServletResponse response,String text){
render(response,"text/xml;charset=UTF-8",text);
}
//发送text
public static void renderText(HttpServletResponse response,String text){
render(response,"text/plain;charset=UTF-8",text);
}
}