Jersey上传服务器---使用

来源:互联网 发布:手机淘宝登录名怎么改 编辑:程序博客网 时间:2024/06/05 05:45

一.Controller

package cn.itcast.core.controller.admin;import java.io.IOException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import java.util.Map.Entry;import java.util.Random;import java.util.Set;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.fckeditor.response.UploadResponse;import org.apache.commons.io.FilenameUtils;import org.json.JSONObject;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import cn.itcast.common.web.ResponseUtils;import cn.itcast.core.web.Constants;import com.sun.jersey.api.client.Client;import com.sun.jersey.api.client.WebResource;/** * 上传图片 * 商品 * 品牌 * 商品介绍Fck * Title: UploadController.java * Description: * @author xwp * @date 2017年5月3日下午9:34:12 * @version 1.0 */@Controllerpublic 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   99for(int i=0 ; i<3 ;i++){format += r.nextInt(10);}//实例化一个JerseyClient client = new Client();//保存数据库String path = "upload/" + format + "." + ext;//另一台服务器的请求路径是?String url = Constants.IMAGE_URL  + path;//设置请求路径WebResource resource = client.resource(url);//发送开始  POST  GET   PUTtry {resource.put(String.class, pic.getBytes());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//返回二个路径JSONObject jo = new JSONObject();jo.put("url", url);jo.put("path",path);ResponseUtils.renderJson(response, jo.toString());}//上传Fck图片@RequestMapping(value = "/upload/uploadFck.do")public void uploadFck(HttpServletRequest request,HttpServletResponse response){//强转request  支持多个MultipartHttpServletRequest mr= (MultipartHttpServletRequest)request;//获取值  支持多个   Map<String, MultipartFile> fileMap = mr.getFileMap();//遍历MapSet<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();for(Entry<String, MultipartFile> entry : entrySet){//上传上来的图片MultipartFile pic = entry.getValue();//扩展名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   99for(int i=0 ; i<3 ;i++){format += r.nextInt(10);}//实例化一个JerseyClient client = new Client();//保存数据库String path = "upload/" + format + "." + ext;//另一台服务器的请求路径是?String url = Constants.IMAGE_URL  + path;//设置请求路径WebResource resource = client.resource(url);//发送开始  POST  GET   PUTtry {resource.put(String.class, pic.getBytes());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//返回Url给Fck   fck-core...jar   ckeditorUploadResponse ok = UploadResponse.getOK(url);//response 返回对象 //response  write //response  print//区别://字符流//字节流try {response.getWriter().print(ok);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

二.ResponseUtils

package cn.itcast.common.web;import java.io.IOException;import javax.servlet.http.HttpServletResponse;/** * 异步返回各种格式 * Title: ResponseUtils.java * Description: * @author xwp * @date 2017年5月3日下午9:35:06 * @version 1.0 */public class ResponseUtils {//发送内容  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 blocke.printStackTrace();}}//发送的是JSONpublic static void renderJson(HttpServletResponse response,String text){render(response, "application/json;charset=UTF-8", text);}//发送xmlpublic static void renderXml(HttpServletResponse response,String text){render(response, "text/xml;charset=UTF-8", text);}//发送textpublic static void renderText(HttpServletResponse response,String text){render(response, "text/plain;charset=UTF-8", text);}}


三.jsp使用

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ include file="/WEB-INF/back_page/head.jsp" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>babasport-add</title><script type="text/javascript">function uploadPic(){//alert(1);//定义参数var options = {url : "/upload/uploadPic.do?",dataType : "json",type :  "post", success : function(data){//回调 二个路径  //url//pathalert(3);$("#allImgUrl").attr("src",data.url);$("#path").val(data.path);}};//jquery.form使用方式$("#jvForm").ajaxSubmit(options);}</script></head><body><div class="box-positon"><div class="rpos">当前位置: 部门管理 - 添加</div><form class="ropt"><input type="submit" onclick="this.form.action='/dept/list.do';" value="返回列表" class="return-button"/></form><div class="clear"></div></div><div class="body-box" style="float:right"><form:form modelAttribute="contentModel" method="post"  id="jvForm" enctype="multipart/form-data" > <table cellspacing="1" cellpadding="2" width="100%" border="0" class="pn-ftable"><tbody><tr><td width="20%" class="pn-flabel pn-flabel-h"><span class="pn-frequired">*</span>公司名:</td><td width="80%" class="pn-fcontent"><form:select path="companyName"><option value="">请选择</option><c:forEach items="${companys }" var="company"><option value="${company.name }">${company.name }</option></c:forEach></form:select><span class="pn-frequired"><form:errors path="companyName"></form:errors></span><span class="pn-frequired">${cpInfo }</span></td></tr><tr><td width="20%" class="pn-flabel pn-flabel-h">部门名:</td><td width="80%" class="pn-fcontent"><form:input path="dname"    /><span class="pn-frequired"><form:errors path="dname"></form:errors></span><span class="pn-frequired">${dpInfo }</span></td></tr><tr><td width="20%" class="pn-flabel pn-flabel-h">地址:</td><td width="80%" class="pn-fcontent"><form:input path="loc"   /><span class="pn-frequired"><form:errors path="loc"></form:errors></span></td></tr></tbody><tbody><tr><td class="pn-fbutton" colspan="2"><input type="submit" class="submit" value="提交"/>   <input type="reset" class="reset" value="重置"/></td></tr></tbody></table></form:form></div></body></html>


四.xml文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><!-- springmvc 扫包  @Controller @Service  .....--><context:component-scan base-package="cn.itcast" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 配置全局日期转换器 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="webBindingInitializer"><bean class="cn.itcast.core.web.CustomDateEdtor"/></property></bean><!-- jsp视图 --><bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/back_page/"/><property name="suffix" value=".jsp"/></bean><!-- 上传图片 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 最大上传尺寸   B    1M --><property name="maxUploadSize"  value="1048576"/></bean></beans>




0 0
原创粉丝点击