有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用API REST通过文件系统上传的java文件

我是JavaEE的新手,我想让用户通过文件系统上传一个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>

我们有一个以上的客户。通过一个简单的获取方法从服务器获取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();
        }

    }

有什么可以解决的方法吗


共 (1) 个答案

  1. # 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可能会帮助你