springmvc 处理json,上传文件,下载文件

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.retrofit</groupId>
	<artifactId>Retrofit</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.2.RELEASE</spring.version>
		<jackson.version>2.8.1</jackson.version>
		<commons-fileupload.version>1.3.1</commons-fileupload.version>
		<commons-lang3.version>3.3.2</commons-lang3.version>
		<commons-io.version>1.3.2</commons-io.version>
		<commons-net.version>3.3</commons-net.version>
		<servlet-api.version>2.5</servlet-api.version>
	</properties>


	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>${servlet-api.version}</version>
			<scope>provided</scope>
		</dependency>

		<!--springmvc 4.x Jackson Json处理工具包 -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

	<!-- springmvc 3.x Jackson Json处理工具包 -->
	<!-- <dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-core-asl</artifactId>
		<version>1.9.13</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency> -->


		<!-- 文件上传组件 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>${commons-fileupload.version}</version>
		</dependency><!-- Apache工具组件 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${commons-lang3.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>${commons-net.version}</version>
		</dependency><!-- spring begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency><!-- spring end -->
	</dependencies>
</project>




web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>springmvc</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- Filter 定义 -->
	<!-- Character Encoding filter -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- springmvc的前端控制器 -->
	<!-- 配置 SpringMVC 的 DispatcherServlet -->
	<!-- The front controller of this Spring Web application, responsible for 
		handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>


</web-app>


springmvc.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<!-- 配置自定扫描的包 -->
	<context:component-scan base-package="com.retrofit"></context:component-scan>

	<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>



	<mvc:annotation-driven />

	<!-- 配置 MultipartResolver -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="maxUploadSize" value="1024000"></property>
	</bean>

</beans>

controller

package com.retrofit;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class RestrofitControllr {

	@Autowired
	private HttpServletRequest request;

	@RequestMapping("/getUser")
	@ResponseBody
	public User getUser(User user) {
		System.out.println(user.toString());
		return user;
	}

	@RequestMapping(value = "/testPost")
	@ResponseBody
	public User getUser1(@RequestBody User user) {
		System.out.println(user);
		return user;
	}

	@RequestMapping(value = "/testPath/{id}")
	@ResponseBody
	public String testPath(@PathVariable Integer id) {
		System.out.println("testPath:" + id);
		return id + "";

	}

	@RequestMapping("/uploadPic")
	@ResponseBody
	public String UpLoadPic(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {

		
		String path = request.getSession().getServletContext().getRealPath("/upload");
		String fileName = file.getOriginalFilename();

		System.out.println(path);
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "ok";
	}

	/***
	 * 保存文件
	 * 
	 * @param file
	 * @return
	 */
	private boolean saveFile(MultipartFile file) {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			String path = request.getSession().getServletContext().getRealPath("upload");
			String fileName = file.getOriginalFilename();

			System.out.println(path);
			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				// 转存文件
				file.transferTo(targetFile);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;

	}

	/**
	 * 多文件上传
	 * @param desciption
	 * @param files
	 * @param username
	 * @return
	 */
	@RequestMapping("filesUpload")
	@ResponseBody
	public String filesUpload(String desciption, @RequestParam("files") MultipartFile[] files, String username) {

		System.out.println(desciption + username);
		// 判断file数组不能为空并且长度大于0
		if (files != null && files.length > 0) {
			// 循环获取file数组中得文件
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 保存文件
				saveFile(file);
			}
		}
		// 重定向
		return "ok";
	}

	/**
	 * 文件下载
	 * 
	 * @param fileName
	 * @param file
	 * @return
	 * @throws IOException
	 * 
	 */
	@RequestMapping("download")
	public ResponseEntity<byte[]> download() throws IOException {

		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName1 = "1.jpg";

		File targetFile = new File(path, fileName1);

		String dfileName = new String(fileName1.getBytes("gb2312"), "iso8859-1");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", dfileName);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(targetFile), headers, HttpStatus.CREATED);
	}

}





string json = ""; string newfilename = ""; string path = ""; try { if (context.Request.Files["file_upload"] != null && context.Request.Files["file_upload"].FileName != "") { string hzm = System.IO.Path.GetExtension(context.Request.Files["file_upload"].FileName);//后缀名 如 .doc string[] a = { ".txt", ".jpg", ".jpeg", ".gif", ".png", ".docx", ".doc", ".xlsx", ".xls", ".rar", ".zip",".pdf" };//设定好了的格式 if (!a.Contains(hzm)) { json = "{\"statusCode\":\"300\",\"message\":\"文件格式不正确\",\"navTabId\":\"nav6\",\"rel\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}"; return json; } else { int defaulsize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["filesize"]);//取得设置的默认文件的大小 int filesize = (context.Request.Files["file_upload"].ContentLength) / 1024; //取得上传的文件的大小,单位为bytes if (filesize < defaulsize) { #region 对文件进行操作 newfilename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + hzm;//文件的新名字 如20120711105734222.doc path = System.Web.HttpContext.Current.Server.MapPath("~/UploadFile//");//文件保存的路径 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } #endregion } else { //超过了文件的大小 json = "{\"statusCode\":\"300\",\"message\":\"上传的文件超过了3000M,请重新选择\",\"navTabId\":\"nav6\",\"rel\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}"; return json; } } } } catch (Exception) { json = "{\"statusCode\":\"300\",\"message\":\"文件格式不正确\",\"navTabId\":\"nav6\",\"rel\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}"; return json; } if (newfilename != "") { context.Request.Files["file_upload"].SaveAs(path + newfilename); //保存文件 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值