2014-11-03 116 views
0

我是Java EE中的新手,我希望用户可以通过文件系统上载文件XML。我的应用程序正在使用API​​ REST。要上传的文件已成功上载到服务器(在本地主机中),但我注意到一些元数据信息是这个新文件的一部分,因此它被卡住了!使用API​​ REST通过文件系统上传的文件

示例:要上传文件“的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(); 
     } 

    } 

任何帮助或窍门,请解决它?

回答

0

同样的问题我已经面临上传JSON

的错误会在你使用写文件作为输出你的地方的正常方法是:是在一个位置,并放置制造x.xml文件内容直接。

正如你从那么应该得到和写在你的方式multipart请求信息发送 与扩展.xml一个文件。

步骤,你应该让你的文件的项目 (无论它们是文件或输入参数)

  • 检查天气的multipart请求做。继续下如果是得到
  • 文件扩展名(不是必要的,但好,如果你选中),然后使用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可能会帮助你。