当前位置: 首页 > 知识库问答 >
问题:

在Java中使用Rest API上传文件

薛焱
2023-03-14

我是REST API的新手。我想上传用户选择的文件到用户提供的路径(远程或本地路径)使用REST API。我的html文件有一个文本框和一个文件选择器。用户将在文本框中输入文件路径(本地或远程计算机文件夹位置)。请建议如何解决这个问题。

下面是我的代码:

<body>
    <form action="rest/file/upload" method="post" enctype="multipart/form-data">
        <p>
            Select a file : <input type="file" name="file" size="45" />
        </p>
        <p>Target Upload Path : <input type="text" name="path" /></p>
        <input type="submit" value="Upload It" />
   </form>
</body>
@Path("/file")
public class UploadFileService {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail,
            @FormParam("path") String path) {

        /*String uploadedFileLocation = "d://uploaded/"                                                                 + fileDetail.getFileName();*/

        /*String uploadedFileLocation = //10.217.14.88/Installables/uploaded/"                                                                  + fileDetail.getFileName();*/
        String uploadedFileLocation = path
                + fileDetail.getFileName();

        // save it
        writeToFile(uploadedInputStream, uploadedFileLocation);

        String output = "File uploaded to : " + uploadedFileLocation;

        return Response.status(200).entity(output).build();

    }

    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream,
            String uploadedFileLocation) {

        try {
            OutputStream out = new FileOutputStream(new File(
                    uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}
<display-name>JAXRSFileUploadJerseyExample</display-name>
<servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.mkyong.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

例外情况:

HTTP Status 500 - com.sun.jersey.api.container.ContainerException: Exception obtaining parameters
type Exception report
message com.sun.jersey.api.container.ContainerException: Exception obtaining parameters
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: com.sun.jersey.api.container.ContainerException: Exception obtaining parameters
        com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:425)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
com.sun.jersey.api.container.ContainerException: Exception obtaining parameters
        com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:54)
        com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125)
        com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
        com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
        com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
        com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
        com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.IllegalStateException: The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded
        com.sun.jersey.server.impl.model.parameter.FormParamInjectableProvider$FormParamInjectable.getValue(FormParamInjectableProvider.java:81)
        com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
        com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125)
        com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
        com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
        com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
        com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
        com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
        com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
        com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
        com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
        com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
        com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
        com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

共有1个答案

易阳云
2023-03-14

我在类下更新了方法的签名,它的工作很好。使用了@formparam而不是@formdataparam(“path”)字符串路径,它解决了我的问题。以下是更新代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/file")
public class UploadFileService {

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("path") String path) {


    // Path format //10.217.14.97/Installables/uploaded/
    System.out.println("path::"+path);
    String uploadedFileLocation = path
            + fileDetail.getFileName();

    // save it
    writeToFile(uploadedInputStream, uploadedFileLocation);

    String output = "File uploaded to : " + uploadedFileLocation;

    return Response.status(200).entity(output).build();

}

// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
        String uploadedFileLocation) {

    try {
        OutputStream out = new FileOutputStream(new File(
                uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

   }

   }
 类似资料:
  • 我使用已签名的URL从使用Air的移动设备上传blob。 我有两个问题: 使用签名 URL 上传 Blob 时,我假设我不需要按照文档中所述包含所有标头。我是否认为我只需要对URL执行请求,并将编码到正文中的文件包含在正文中,设置为? http://msdn . Microsoft . com/en-us/library/windows azure/DD 179451 . aspx (Upload

  • 问题内容: 谁能让我知道如何使用Java代码使用Selenium上传文件? 当我单击应用程序中的按钮时,它将在新窗口中打开,可以用来选择上传文件。Silverlight(C#)开发的浏览按钮。 问题答案: 首先确保输入元素可见 正如Mark Collin在此处的讨论中所述: 不要单击浏览按钮,它会触发操作系统级别的对话框并有效地停止测试。 相反,你可以使用: myUploadElement是该元素

  • 谁能让我知道如何通过Java代码使用Selenium上传文件? 当我点击应用程序中的按钮时,它会在新窗口中打开,我可以用它来选择上传文件。Silverlight(C#)开发的浏览按钮。

  • 我正在尝试使用多部分实体方法上传文件。但它失败,错误说{“错误”:“文件参数值'无'无效”} 我的代码是: File File = new File(" C:/Users/SST-06/Desktop/new . txt "); 我的实体文件包含所有提到的参数。 -hkYO-pblk 0 uqlxjtvklrbkosxz 7 mye-8 wbvbvanx Content-Disposition:f

  • 问题内容: 我是REST API的新手。我想使用REST API将用户选择的文件上传到用户提供的路径(远程或本地路径)。我的html文件具有1个文本框和1个文件选择器。用户将在文本框中输入FilePath(本地或远程计算机文件夹位置)。请提出如何解决此问题的建议。 这是我的代码: FileUpload.html :: UploadFileService.java Web.xml 例外: 问题答案:

  • 问题内容: 如何使用Ajax在Struts 2中上传文件 问题答案: 下载Struts2 jQuery插件 ,并像通常使用Struts2一样进行操作。