【问题标题】:File Uploaded via File System using API REST使用 API REST 通过文件系统上传的文件
【发布时间】:2014-12-30 10:33:02
【问题描述】:

我是 Java EE 的新手,我希望用户通过其文件系统上传文件 XML。我的应用正在使用 API REST。要上传的文件已成功上传到服务器(在 localhost 中),但我注意到一些元数据信息是这个新文件的一部分,所以它卡在那里!

示例:上传文件“web.xml”,这里是添加到新文件头和尾的内容(服务器端)

Header:
------WebKitFormBoundarybi7qp5AIFEXbebt7
Content-Disposition: form-data; name="datafile"; filename="web.xml"
Content-Type: text/xml

End of new file
------WebKitFormBoundarybi7qp5AIFEXbebt7--

参见下面的 HTML 客户端文件和服务器端代码

Client.HTML

</body>
<form action="rest/file/upload" enctype="multipart/form-data" method="post">
    <p>
        Entrer un fichier xml:<br>
        <input type="file" name="datafile" size="40">
    </p>
    <div>
        <input type="submit" value="Send">
    </div>
</form>
</body>

我们通过服务器的简单 GET 方法在“Client.HTML”上方得到了这个。提交表单时,调用下面的POST方法

UploadService.java
@Path("/file")
public class UploadService {
@POST
@Path("/upload")
@Produces("text/html")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@Context HttpServletRequest request) {
    String uploadedFileLocation = "D:\\rest.xml";

    InputStream in;
    try {

        in = request.getInputStream();
        // save it
        writeToFile(in, uploadedFileLocation);

    } catch (IOException e) {

    }
    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];

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

            e.printStackTrace();
        }

    }

请问有什么解决方法或技巧吗?

【问题讨论】:

    标签: java rest upload header jax-rs


    【解决方案1】:

    我在上传JSON时遇到了同样的问题

    错误可能是您使用将文件作为输出写入您的位置的常规方法是通过在某个位置创建x.xml文件并将直接内容。

    当您从多部分请求中发送扩展名为 .xml 的文件时 所以应该用这种方式获取和编写。

    获取文件项应执行的步骤 (要么是文件参数,要么是输入参数)

    • 检查天气,它是一个多部分请求。如果是,则继续下一步获取
    • 文件扩展名(没有必要,但如果你检查一下很好)然后阅读它
    • 内容使用parseRequest method
    • 然后将其内容写入文件。

      boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { out.println("You are not trying to upload<br/>"); return; out.println("You are trying to upload<br/>");

    供参考您可以查看this,但它仅适用于普通文件,不适用于xml。 uploading xml 也可以帮到你。

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2023-03-10
      • 2014-09-16
      • 2021-06-07
      • 1970-01-01
      • 2016-12-14
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多