java 跨域附件上传

时间:2022-08-29 08:41:38

1、首先,在pom中加入依赖

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>3.2.3.RELEASE</org.springframework.version>
</properties>


<repositories>
<repository>
<id>repository.jboss.org</id>
<name>JBoss Public Maven Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>Spring Maven Repository</id>
<url>http://repo.spring.io/release/</url>
</repository>
<repository>
<id>codehaus</id>
<name>codehaus</name>
<url>http://repository.codehaus.org/</url>
</repository>
<repository>
<id>sonatype</id>
<name>Sonatype Repository</name>
<url>http://repository.sonatype.org/content/groups/public/</url>
</repository>
</repositories>


<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>


<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.4.3</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<finalName>gfile</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>

</project>

2、配置文件,注意黄色标注的过滤器是必需的

(1)web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


<web-app>
<display-name>Archetype Created Web Application</display-name>

<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>com.**.common.SimpleCORSFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

(2)dispatcher-servlet.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:ctx="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
default-autowire="byName"
xsi:schemaLocation="
  http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           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.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


<ctx:component-scan base-package="com.**.controller" />
<ctx:annotation-config />
<mvc:annotation-driven />


<mvc:resources mapping="/**" location="/" />


<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>


<bean id="annexFilePath" class="com.gbits.file.common.AnnexFilePath">
<property name="physicalPath" value="E:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\gfile\\files\\"/>
</bean>

<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">


<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml" />
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="file" value="multipart/form-data" />
</map>
</property>


<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".html" />
</bean>
</list>
</property>


<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>


</bean>
</beans>

3、过滤器的实现

public class SimpleCORSFilter implements Filter{


@Override
public void destroy() {

}


@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}


@Override
public void init(FilterConfig arg0) throws ServletException {

}
}

4、文件处理程序

@Controller
@RequestMapping(value = "/file")
public class FileUploaderController {


private static Logger log = Logger.getLogger(FileUploaderController.class);
@Autowired
private AnnexFilePath annexFilePath;


@RequestMapping(value = "/uploadImageNewsImage")
@ResponseBody
public Object handleFileUpload(HttpServletRequest request,
@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,@RequestParam("type") String type) throws Exception {
log.info(String.format("name:%s,type:%s", name,type));
Map<Object, Object> map = new HashMap<Object, Object>();
if (!file.isEmpty()) {
BufferedOutputStream stream = null;
try {
byte[] bytes = file.getBytes();
final String subDir = type+File.separator + DateUtils.getDateStrCompact(new Date());
File dir = new File(annexFilePath.getPhysicalPath()+subDir);
if (!dir.exists()) {
log.info("make file dir : "+dir.getAbsolutePath());
dir.mkdirs();
}


String suffix = name.substring(name.indexOf("."));
String fileName = UUID.randomUUID() + suffix;
File upload = new File(dir, fileName);
stream = new BufferedOutputStream(
new FileOutputStream(upload));
stream.write(bytes);
if(upload.length() > 0){
log.info(String.format("%s successfully uploaded.", name));
}else{
log.info(String.format("%s upload failed.", name));
}
String imageUrl = subDir + File.separator + fileName;
map.put("success", true);
map.put("imageUrl", imageUrl);


} catch (Exception e) {
log.error(e);
String errorMsg = "You failed to upload " + name + " => "
+ e.getMessage();
map.put("success", false);
map.put("errorMsg", errorMsg);
} finally{
try {
if(stream != null)
stream.close();
} catch (Exception e2) {
log.error(e2);
}
}
} else {
String errorMsg = "You failed to upload " + name
+ " because the file was empty.";
map.put("success", false);
map.put("errorMsg", errorMsg);
log.error(errorMsg);
}
return map;
}

@RequestMapping(value = "/test")
@ResponseBody
public Object test(){
return "aaaaaaaaaaa";
}
}


public final class AnnexFilePath {


/**
* @fieldName: physicalPath
* @fieldType: String
* @Description: 物理路径
*/
private String physicalPath;




/**
* @return the physicalPath
*/
public String getPhysicalPath() {
return physicalPath;
}


/**
* @param physicalPath the physicalPath to set
*/
public void setPhysicalPath(String physicalPath) {
this.physicalPath = physicalPath;
}
}

5、前端

(1)html


<form id="imgForm">
<input type="hidden" name="name" id="name" value="{{fileName}}">
<input type="hidden" name="type" id="type" value="circle_icon">
<input type="file" name="file" id="file" g-value="fileName" ng-model="file">
</form>


(2)js

var formData = new FormData($("#imgForm")[0]);

$.ajax({
           url : "http://ip:port/fileserver/file/uploadImageNewsImage",
           type: "POST",
           data: formData,
           cache: false,
           contentType: false,
           processData: false,
           success:function(data){
            if (data.errorMsg == undefined) {
            if (data.success) {
            console.log(data);
            }
            }
           }
    });