使用Restlet中的描述文件上传 [英] File Upload with Description in Restlet

查看:238
本文介绍了使用Restlet中的描述文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 restlet 上传文件和其他一些数据。所以我创建了一个如下所示的html页面。

 < html> 
< body>
< h1> *****用RESTFul WebService上传文件*****< / h1>
< form action =http:// localhost:8080 / test / api / streams / sample.jsonmethod =postenctype =multipart / form-data>


< fieldset>
<图标>上传文件< / legend>

< input type =filename =fileToUpload/>< br />
< br />< br />
派对ID< input type =textname =mybody/>< br />


< input type =submitname =Uploadid =Uploadvalue =Upload/>
< / fieldset>
< / form>
< / body>



我需要读取值来自输入字段以及文件数据。现在可以读取文件内容了。我可以从相同的api调用中的输入框中获取值。

  @Post 
public表示接受(表示实体)抛出异常{
表示结果= null;


if(entity!= null){
if(MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(),true)){
// 1 /为基于磁盘的文件项创建一个工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000240);

// 2 /根据Restlet
创建一个新的文件上传处理程序// FileUpload扩展将解析Restlet请求,
//生成FileItems。
RestletFileUpload upload = new RestletFileUpload(factory);

// 3 / Request被处理程序解析,该处理程序生成一个
// FileItems列表
FileItemIterator fileIterator = upload.getItemIterator(entity);

//仅处理上传的文件fileToUpload
//并返回
boolean found = false;
while(fileIterator.hasNext()&&!found){
FileItemStream fi = fileIterator.next();
Extractor extractor = new Extractor(getContext()); $()
$ b if(fi.getFieldName()。equals(fileToUpload)){
found = true;
//立即消耗流,否则流
//将被关闭。
StringBuilder sb = new StringBuilder(media type:);
sb.append(fi.getContentType())。append(\\\
);
sb.append(file name:);
sb.append(fi.getName())。append(\\\
);
BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream()));
String line = null; ((line = br.readLine())!= null){
sb.append(line);
while
}
sb.append(\\\
);
result = new StringRepresentation(sb.toString(),MediaType.TEXT_PLAIN);
}
}
} else {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
}
System.out.println(result ==+ result);
}


返回结果;

}

解决方案首先你需要了解你的请求的内容。如果你看看发送的请求(firebug或其他),你会看到以下内容:

   - --------------------------- 2003194375274723921294130757 
Content-Disposition:form-data; NAME = fileToUpload;
filename =mysql.sql内容类型:application / sql

<<您的文件内容>>
----------------------------- 2003194375274723921294130757
Content-Disposition:form-data; name =mybody

我的价值
----------------------------- 2003194375274723921294130757
内容处理:表单数据; name =上传

上传
----------------------------- 2003194375274723921294130757--

正如您所看到的,您的请求中有几个部分。这意味着您可以遍历服务器资源中的这些部分。在你提供的代码中,你只能找到名字为 fileToUpload 的条目,当找到的时候,你打破了循环。



<你可以更新你的代码来完成整个循环,并检查输入字段的值 mybody ,如下所示:

  while(fileIterator.hasNext()){
FileItemStream fi = fileIterator.next();

if(mybody.equals(fi.getFieldName())){
BufferedReader br = new BufferedReader(
new InputStreamReader(fi.openStream()));
String fieldValue = null; $(
)if((line = br.readLine())!= null){
fieldValue = line; (...)

} else if(fileToUpload.equals(fi.getFieldName())){
(...)
}
(...)

$ / code>

希望它有帮助,
Thierry


I need to upload a file with some additional data using restlet. So i create a sample html page like below.

<html>
<body>
    <h1>*****Upload File with RESTFul WebService*****</h1>
    <form action="http://localhost:8080/test/api/streams/sample.json" method="post" enctype="multipart/form-data">


        <fieldset>
            <legend>Upload File</legend>

            <input type="file" name="fileToUpload"/><br />  
            <br /><br />
            Party ID<input type="text" name="mybody"  /><br />


            <input type="submit" name="Upload" id="Upload" value="Upload" />
        </fieldset>
    </form>
</body>

I need to read the value from input field along with the file data.Now it is possible to read the file content.how can i get value from that input box in the same api call.

@Post
public Representation accept(Representation entity) throws Exception {
Representation result = null;


if (entity != null) {
  if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240);

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    // 3/ Request is parsed by the handler which generates a
    // list of FileItems
    FileItemIterator fileIterator = upload.getItemIterator(entity);

    // Process only the uploaded item called "fileToUpload"
    // and return back
    boolean found = false;
    while (fileIterator.hasNext() && !found) {
      FileItemStream fi = fileIterator.next();
      Extractor extractor = new Extractor(getContext());

      if (fi.getFieldName().equals("fileToUpload")) {
        found = true;
        // consume the stream immediately, otherwise the stream
        // will be closed.
        StringBuilder sb = new StringBuilder("media type: ");
        sb.append(fi.getContentType()).append("\n");
        sb.append("file name : ");
        sb.append(fi.getName()).append("\n");
        BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
          sb.append(line);
        }
        sb.append("\n");
        result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN);
      }
    }
  } else {
    setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
  }
  System.out.println("result==" + result);
}


return result;

}

解决方案

First you need to understand the content of your request. If you have a look at the sent request (firebug or something else), you'll see the following content:

-----------------------------2003194375274723921294130757
Content-Disposition: form-data; name="fileToUpload";
filename="mysql.sql" Content-Type: application/sql 

<<YOUR FILE CONTENT>>
-----------------------------2003194375274723921294130757
Content-Disposition: form-data; name="mybody"

my value
-----------------------------2003194375274723921294130757
Content-Disposition: form-data; name="Upload"

Upload
-----------------------------2003194375274723921294130757--

As you can see there are several parts in your request. This means that you can iterate over these parts in your server resource. In the code you provide, you only look for the entry with name fileToUpload and when found, you break the loop.

You can update your code to do the complete loop and check the value mybody for your input field, as described below:

while (fileIterator.hasNext()) {
    FileItemStream fi = fileIterator.next();

    if ("mybody".equals(fi.getFieldName())) {
        BufferedReader br = new BufferedReader(
                 new InputStreamReader(fi.openStream()));
        String fieldValue = null;
        if ((line = br.readLine()) != null) {
            fieldValue = line;
        }
    } else if ("fileToUpload".equals(fi.getFieldName())) {
        (...)
    }
    (...)
}

Hope it helps, Thierry

这篇关于使用Restlet中的描述文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆