基于Java中两种jersey文件上传方式
本文将带领大家使用基于jax-rs rest风格的实现jersey来上传文件到服务器制定的文件夹,如果是图片并读取显示出该图片。
准备工作:准备一个form表单,有两个字段,一个是type="file"和type="text",并且表单需要使用post方式提交。注意改表单需要使用multipart/form-data
。该项目使用netbeans8.0和glassfish4.0开发和运行。并且使用maven管理该工程;需要在您的c盘建立一个文件夹,用来存储上传的文件。如c:\newsportal\article_images开发环境:1 创建工程 在你项目空白处右键-》点击新建项目
2 在创建的项目中选择maven-》点击右侧web应用程序
3 填写工程的名字和maven的组id和包名
4 选择该项目的运行环境为服务器glassfish server
5 最后点击完成
准备搭建jersey的运行环境:
1 配置maven需要依赖包,maven的pom文件依赖如下:
<?xml version="1.0" encoding="utf-8"?>
<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 ">
<modelversion>4.0.0</modelversion>
<groupid>com.vi8</groupid>
<artifactid>jerseyuploaddemo</artifactid>
<version>1.0-snapshot</version>
<packaging>war</packaging>
<name>jerseyuploaddemo</name>
<description>
jersey上传文件dmeo
</description>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceencoding>utf-8</project.build.sourceencoding>
</properties>
<dependencies>
<!-- jersey -->
<dependency>
<groupid>org.glassfish.jersey.core</groupid>
<artifactid>jersey-server</artifactid>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupid>org.glassfish.jersey.ext</groupid>
<artifactid>jersey-mvc-jsp</artifactid>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupid>org.glassfish.jersey.media</groupid>
<artifactid>jersey-media-json-jackson</artifactid>
<version>2.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!-- 上传文件需要该依赖-->
<dependency>
<groupid>org.glassfish.jersey.media</groupid>
<artifactid>jersey-media-multipart</artifactid>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- 这个用于上传文件工具操作-->
<dependency>
<groupid>commons-io</groupid>
<artifactid>commons-io</artifactid>
<version>2.4</version>
</dependency>
<dependency>
<groupid>javax</groupid>
<artifactid>javaee-web-api</artifactid>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-compiler-plugin</artifactid>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerarguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerarguments>
</configuration>
</plugin>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-war-plugin</artifactid>
<version>2.3</version>
<configuration>
<failonmissingwebxml>false</failonmissingwebxml>
</configuration>
</plugin>
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-dependency-plugin</artifactid>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputdirectory>${endorsed.dir}</outputdirectory>
<silent>true</silent>
<artifactitems>
<artifactitem>
<groupid>javax</groupid>
<artifactid>javaee-endorsed-api</artifactid>
<version>7.0</version>
<type>jar</type>
</artifactitem>
</artifactitems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2 配置web.xml用以支持jersey,配置如下:
<?xml version="1.0" encoding="utf-8"?>
<web-app version="3.1" xmlns="" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation=" ">
<filter>
<filter-name>jerseyfilter</filter-name>
<filter-class>org.glassfish.jersey.servlet.servletcontainer</filter-class>
<init-param>
<param-name>javax.ws.rs.application</param-name>
<!--myapplication.java jersey加载-->
<param-value>com.vi8.upload.myapplication</param-value>
</init-param>
<init-param>
<param-name>jersey.config.servlet.filter.staticcontentregex</param-name>
<param-value>/(img|css|js|font)/.*</param-value>
</init-param>
<init-param>
<param-name>jersey.config.servlet.filter.forwardon404</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.mvc.templatebasepath.jsp</param-name>
<param-value>/web-inf/pages</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jerseyfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3 编写上面web.xml用到的myapplication.java 如下:
package com.vi8.upload;
import javax.ws.rs.applicationpath;
import org.glassfish.jersey.jackson.jacksonfeature;
import org.glassfish.jersey.media.multipart.multipartfeature;
import org.glassfish.jersey.server.resourceconfig;
import org.glassfish.jersey.server.mvc.jsp.jspmvcfeature;
/**
* qq:
*
* @author administrator
*/
@applicationpath("/")
public class myapplication extends resourceconfig {
public myapplication() {
packages("com.vi8.upload.resources");
register(jspmvcfeature.class);
register(jacksonfeature.class);
register(multipartfeature.class);
}
}
以上步骤基本就是jersey运行环境准备工作,接下开始讨论文件如何上传的。
jersey文件上传:
1 文件上传的resource类,你可以理解是spring mvc中控制器。uploadimageresource.java清单代码
package com.vi8.upload.resources;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.unsupportedencodingexception;
import java.util.calendar;
import java.util.logging.level;
import java.util.logging.logger;
import javax.servlet.http.httpservletresponse;
import javax.ws.rs.consumes;
import javax.ws.rs.get;
import javax.ws.rs.post;
import javax.ws.rs.path;
import javax.ws.rs.pathparam;
import javax.ws.rs.produces;
import javax.ws.rs.core.context;
import javax.ws.rs.core.mediatype;
import org.apache.commons.io.fileutils;
import org.glassfish.jersey.media.multipart.contentdisposition;
import org.glassfish.jersey.media.multipart.formdatabodypart;
import org.glassfish.jersey.media.multipart.formdatacontentdisposition;
import org.glassfish.jersey.media.multipart.formdatamultipart;
import org.glassfish.jersey.media.multipart.formdataparam;
@path("upload")
public class uploadimageresource {
/**
* constants operating with images
*/
private static final string article_images_path = "c:/newsportal/article_images/";
private static final string jpg_content_type = "image/jpeg";
private static final string png_content_type = "image/png";
/**
* 第一种方式上传
*
* @param fileinputstream
* @param disposition
* @return
*/
@post
@path("uploadimage1 ")
@consumes(mediatype.multipart_form_data)
public string uploadimage1(@formdataparam("file") inputstream fileinputstream,
@formdataparam("file") formdatacontentdisposition disposition) {
string imagename = calendar.getinstance().gettimeinmillis()
+ disposition.getfilename();
file file = new file(article_images_path + imagename);
try {
//使用common io的文件写入操作
fileutils.copyinputstreamtofile(fileinputstream, file);
//原来自己的文件写入操作
//savefile(fileinputstream, file);
} catch (ioexception ex) {
logger.getlogger(uploadimageresource.class.getname()).log(level.severe, null, ex);
}
return "images/" + imagename;
}
/**
* *
* 第二种方式上传 使用formdatamultipart 获取表单数据
*
* @param form
* @param response
* @return
* @throws unsupportedencodingexception
*/
@post
@path("uploadimage2")
@consumes(mediatype.multipart_form_data)
@produces(mediatype.application_json)
public string uploadimage2(formdatamultipart form, @context httpservletresponse response) throws unsupportedencodingexception {
//获取文件流
formdatabodypart filepart = form.getfield("file");
//获取表单的其他数据
formdatabodypart usernamepart = form.getfield("username");
//contentdisposition headeroffilepart = filepart.getcontentdisposition();
//把表单内容转换成流
inputstream fileinputstream = filepart.getvalueas(inputstream.class);
formdatacontentdisposition formdatacontentdisposition = filepart.getformdatacontentdisposition();
string source = formdatacontentdisposition.getfilename();
string result = new string(source.getbytes("iso8859-1"), "utf-8");
system.out.println("formdatacontentdisposition.getfilename()result " + result);
string filepath = article_images_path + result;
file file = new file(filepath);
system.out.println("file " + file.getabsolutepath());
try {
//保存文件
fileutils.copyinputstreamtofile(fileinputstream, file);
// savefile(fileinputstream, file);
} catch (ioexception ex) {
logger.getlogger(uploadimageresource.class.getname()).log(level.severe, null, ex);
}
system.out.println("" + "images/" + result);
response.setcharacterencoding("utf-8");
return "images/" + result;
}
/**
*
* 不从web服务器去读图片,在磁盘某个目录的文件可以通过流的方式去获取 ,通过 response.getoutputstream()放回数据
*
* @param imagename image-name
* @param type extension of image
* @param response {@link httpservletresponse}
* @throws ioexception
*/
@get
@path("/images/{name}.{type}")
public void showimg(@pathparam("name") string imagename,
@pathparam("type") string type,
@context httpservletresponse response)
throws ioexception {
system.out.println("showimg");
try (inputstream in = new fileinputstream(article_images_path
+ imagename + "." + type)) {
fileutils.copyfile(new file(article_images_path + imagename + "." + type), response.getoutputstream());
// filecopyutils.copy(in, response.getoutputstream());
}
}
// 保存文件信息到磁盘
private void savefile(inputstream uploadedinputstream, file file) {
system.out.println("------savefile-----");
try {
outputstream outpustream = new fileoutputstream(file);
int read = 0;
byte[] bytes = new byte[1024];
// outpustream = new fileoutputstream(new file(serverlocation));
while ((read = uploadedinputstream.read(bytes)) != -1) {
outpustream.write(bytes, 0, read);
}
outpustream.flush();
outpustream.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
2 当然要测试你也许还需要准备一个带有form表单的jsp文件
<form action="${pagecontext.request.contextpath}/upload/uploadimage2" method="post" enctype="multipart/form-data">
<p>
文件 :<input type="file" name="file"/><br />
用户名: <input type="text" name="username"/><br />
</p>
<input type="submit" value="上传" />
</form>
结果如下
以上就是本文的全部内容,希望对大家实现jersey文件上传有所帮助。