框架使用springmvc 、jersey,单独的文件上传服务器为tomcat,使用
在springmvc.xml文件中配置解析器
<!--解析器配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置文件的最大上尺寸-->
<value>1024000</value>
<span style="font-family: Arial, Helvetica, sans-serif;"></bean></span>
需要在文件上传服务器的web.xml default sevlet中加入:
<init-param>
<span style="font-family: Arial, Helvetica, sans-serif;"> <param-name>readonly</param-name></span>
<param-value>false</param-value>
<init-param>
页面需要添加
<from method="post" enctype="multipart/form-data ></from>
controller中:
public void uploadPic(HttpServletRequest request, Writer out) throws IOException{
//把request转换成复杂request
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
</span>//获得文件
Map<String, MultipartFile> map = mr.getFileMap();
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
String fileInputName = it.next();
MultipartFile mf = map.get(fileInputName);
//获得文件的字节数组
byte [] bs = mf.getBytes();
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String oriFileName = mf.getOriginalFilename();
//获得文件的后缀
String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
//获得上传文件的绝对路径
String realPath = UploadUtils.readProp("file_path")+"/upload/"+fileName+suffix;
//获得相对路径
String relativePath = "/upload/"+fileName+suffix;
//创建jersy的客户端
Client client = Client.create();
//创建web资源对象
WebResource wr = client.resource(realPath);
//上传
wr.put(bs);
JSONObject jo = new JSONObject();
jo.accumulate("realPath", realPath);
jo.accumulate("relativePath", relativePath);
String result = jo.toString();
out.write(result);
}
UploadUtils中:通过properties文件获取上传地址
public static String redaProp(String key){
InputStream in=UploadUtils.class.getClassLoader().getResourceAsStream("system.properties");
Properties properties=new Properties();
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty(key);
}
system.properties文件:
file_path=http://localhost:8080/upload-file