通过rest和html作为客户端上传文件

问题描述 投票:2回答:1

我只想使用jersey rest服务和Jquery ajax作为客户端上传文件,这是我的代码1。HTML

<form action="rest/file/upload" method="post" enctype="multipart/form-data">

   <p>
    Select a file : <input type="file" name="file" />
   </p>

   <input type="submit" value="Upload It" />
</form>

2.休息服务

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream stream) {

    String uploadedFileLocation = "E:\\\\uploaded\\test.jpg";
    //Session s = Session.getDefaultInstance(new Properties());
    //InputStream is = new ByteArrayInputStream(<< String to parse >>);
    //MimeMessage message = new MimeMessage(s, stream);
    //Multipart multipart = (Multipart) message.getContent();
    // save it



    writeToFile(stream, uploadedFileLocation);


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

    try {

        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

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

}

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

    try {
        byte[] image = IOUtils.toByteArray(uploadedInputStream);


        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));

        IOUtils.write(image, out);

        /*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();
    }

}

它的工作,但流也包括这条线

-----------------------------7dd3b827a0ddc

内容处置:表单数据; NAME = “文件”; filename =“ Jellyfish.jpg”内容类型:image / pjpeg

如何从输入流中删除呢? 需要专业知识答案

java html rest multipartform-data fileinputstream
1个回答
1
投票

您看到的此字符串是服务器添加的一种标识符,用于标记表单中上传的数据的开始和结束。 如果将整个数据转储到文本文件中,它将在文本文件中显示类似的内容。

Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=-----------------------------7dd3b827a0ddc
Content-Length: 29278

-----------------------------7dd3b827a0ddc
Content-Disposition: form-data; name="txt1"

Some Sample Text
-----------------------------7dd3b827a0ddc
Content-Disposition: form-data; name="file"; filename="Jellyfish.jpg" Content-Type: image/jpeg

(Binary data not shown)
-----------------------------7dd3b827a0ddc--

边界的值,即----------------------------- 7dd3b827a0ddc是一个标记,多部分表单数据用于标识开始和结束整体上传中所有字段的数据。

我为您创建了此样本文件,并假设一个文件上传并且输入文本名为txt1。

在数据文件上,您可以看到标题中的“边界”,然后是用于分隔表单数据中两个字段的边界。 请注意最后一个边界上的额外“-”。 那标志着文件的结尾。

您需要手动解析数据并提取所有字段。 您在其中具有filename =“ Jellyfish.jpg”的标记之间的数据是为您的图像上传的实际二进制数据。 当您从两个标记之间提取该数据(“ Content-Disposition:form-data; name =“ file”; filename =“ Jellyfish.jpg” Content-Type:image / jpeg“除外)并将该数据另存为“ Jellyfish.jpg“; 这将是你的形象。

© www.soinside.com 2019 - 2024. All rights reserved.