Jersey上传服务器---使用

一.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
 */
@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());
	}
	//上传Fck图片
	@RequestMapping(value = "/upload/uploadFck.do")
	public void uploadFck(HttpServletRequest request,HttpServletResponse response){
		//强转request  支持多个
		MultipartHttpServletRequest mr= (MultipartHttpServletRequest)request;
		//获取值  支持多个   
		Map<String, MultipartFile> fileMap = mr.getFileMap();
		//遍历Map
		Set<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   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();
			}
			//返回Url给Fck   fck-core...jar   ckeditor
			UploadResponse ok = UploadResponse.getOK(url);
			//response 返回对象 
			//response  write 
			//response  print
			//区别:
			//字符流
			//字节流
			try {
				response.getWriter().print(ok);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.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 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);
	}
	
	
}


三.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
			//path
			alert(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" οnclick="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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值