最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Java中兩種jersey文件上傳方式

 更新時間:2016年01月27日 15:55:04   作者:一名清官  
這篇文章主要介紹了基于Java中兩種jersey文件上傳方式的相關(guān)資料,需要的朋友可以參考下

本文將帶領(lǐng)大家使用基于JAX-RS REST風(fēng)格的實現(xiàn)Jersey來上傳文件到服務(wù)器制定的文件夾,如果是圖片并讀取顯示出該圖片。

準(zhǔn)備工作:準(zhǔn)備一個form表單,有兩個字段,一個是type="file"和type="text",并且表單需要使用POST方式提交。注意改表單需要使用multipart/form-data。該項目使用netbeans8.0和glassfish4.0開發(fā)和運行。并且使用maven管理該工程;需要在您的C盤建立一個文件夾,用來存儲上傳的文件。如C:\Newsportal\article_images開發(fā)環(huán)境:1 創(chuàng)建工程 在你項目空白處右鍵-》點擊新建項目

            

2 在創(chuàng)建的項目中選擇maven-》點擊右側(cè)web應(yīng)用程序


3 填寫工程的名字和maven的組ID和包名


4 選擇該項目的運行環(huán)境為服務(wù)器Glassfish server

5 最后點擊完成
準(zhǔn)備搭建jersey的運行環(huán)境:
1 配置maven需要依賴包,maven的pom文件依賴如下:
<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="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="
http://xmlns.jcp.org/xml/ns/javaee     <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:
845885222@qq.com
 *
 * @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運行環(huán)境準(zhǔn)備工作,接下開始討論文件如何上傳的。
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 獲取表單數(shù)據(jù)
     *
     * @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"); 
    //獲取表單的其他數(shù)據(jù) 
    FormDataBodyPart usernamePart = form.getField("username"); 
 
    //ContentDisposition headerOfFilePart = filePart.getContentDisposition(); 
    //把表單內(nèi)容轉(zhuǎn)換成流 
    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服務(wù)器去讀圖片,在磁盤某個目錄的文件可以通過流的方式去獲取 ,通過 response.getOutputStream()放回數(shù)據(jù)
     *
     * @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 當(dāng)然要測試你也許還需要準(zhǔn)備一個帶有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> 

結(jié)果如下

以上就是本文的全部內(nèi)容,希望對大家實現(xiàn)jersey文件上傳有所幫助。

相關(guān)文章

  • jvm信息jmap使用的基本方法教程

    jvm信息jmap使用的基本方法教程

    JDK本身提供了很多方便的JVM性能調(diào)優(yōu)監(jiān)控工具,除了集成式的VisualVM和jConsole外,還有jps、jstack、jmap、jhat、jstat等小巧的工具,下面這篇文章主要給大家介紹了關(guān)于jvm信息jmap使用的基本方法教程,需要的朋友可以參考下
    2018-08-08
  • Java線程狀態(tài)及同步鎖的操作方法

    Java線程狀態(tài)及同步鎖的操作方法

    Java中的thread類自帶有線程的一些方法,這些方法可以讓線程睡眠,插隊,提高線程調(diào)度的優(yōu)先級等等,它們提供了改變線程狀態(tài)的操作手段,這篇文章主要介紹了Java線程狀態(tài)及同步鎖,需要的朋友可以參考下
    2021-11-11
  • 關(guān)于spring版本與JDK版本不兼容的問題及解決方法

    關(guān)于spring版本與JDK版本不兼容的問題及解決方法

    這篇文章主要介紹了關(guān)于spring版本與JDK版本不兼容的問題,本文給大家?guī)砹私鉀Q方法,需要的朋友可以參考下
    2018-11-11
  • Springboot實現(xiàn)Java郵件任務(wù)過程解析

    Springboot實現(xiàn)Java郵件任務(wù)過程解析

    這篇文章主要介紹了Springboot實現(xiàn)Java郵件任務(wù)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • SpringMVC4.3?HttpMessageConverter接口實現(xiàn)源碼分析

    SpringMVC4.3?HttpMessageConverter接口實現(xiàn)源碼分析

    這篇文章主要為大家介紹了SpringMVC4.3?HttpMessageConverter接口實現(xiàn)源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-09-09
  • java7 簡化變參方法調(diào)用實例方法

    java7 簡化變參方法調(diào)用實例方法

    在本篇文章里我們給大家整理的是關(guān)于java7 簡化變參方法調(diào)用實例方法以及實例代碼,需要的朋友們學(xué)習(xí)下。
    2019-11-11
  • Java異常java.lang.UnsatisfiedLinkError: no opencv_java320 in java.library.path的解決

    Java異常java.lang.UnsatisfiedLinkError: no opencv_ja

    這篇文章主要介紹了Java異常java.lang.UnsatisfiedLinkError: no opencv_java320 in java.library.path的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • 詳解DES加密算法的原理與Java實現(xiàn)

    詳解DES加密算法的原理與Java實現(xiàn)

    DES 加密,是對稱加密。對稱加密,顧名思義,加密和解密的運算全都是使用的同樣的秘鑰。這篇文章主要為大家講講DES加密算法的原理與Java實現(xiàn),需要的可以參考一下
    2022-10-10
  • springMvc異步的DeferredResult long?polling應(yīng)用示例解析

    springMvc異步的DeferredResult long?polling應(yīng)用示例解析

    這篇文章主要為大家介紹了springMvc中DeferredResult的long?polling應(yīng)用示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-03-03
  • Spring基于注解的緩存聲明深入探究

    Spring基于注解的緩存聲明深入探究

    spring boot對緩存支持非常靈活,我們可以使用默認(rèn)的EhCache,也可以整合第三方的框架,只需配置即可,下面這篇文章主要給大家介紹了關(guān)于SpringBoot學(xué)習(xí)之基于注解緩存的相關(guān)資料,需要的朋友可以參考下
    2022-08-08

最新評論

阿图什市| 镇原县| 樟树市| 砚山县| 宜良县| 高州市| 南澳县| 南安市| 乌兰浩特市| 西安市| 县级市| 民和| 桂林市| 泰兴市| 专栏| 资溪县| 武功县| 潍坊市| 和静县| 甘孜| 依兰县| 广德县| 云阳县| 恭城| 太和县| 武山县| 百色市| 古丈县| 旺苍县| 旅游| 科尔| 兴安盟| 中西区| 静安区| 滦平县| 微博| 达日县| 巫山县| 观塘区| 讷河市| 民县|