使用NanoHttpd从POST请求中检索文件 [英] Retrieve file from POST request with NanoHttpd
问题描述
我正在尝试使用NanoHttpd库通过表单中的POST请求将文件上传到我的Android服务器。我确实收到了服务器端的POST请求。我的问题是如何从POST请求中检索文件,以便将其保存在设备内存中的某个位置。
I am trying to use the NanoHttpd library to upload files to my Android server by using a POST request from a form. I do receive the POST request on the server side. My question is how to retrieve the file from the POST request so I can save it somewhere in the device memory.
表单:
<form action='?' method='post' enctype='multipart/form-data'>
<input type='file' name='file' />`enter code here`
<input type='submit'name='submit' value='Upload'/>
</form>
服务方式:
@Override
public Response serve (IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
if (Method.POST.equals(method)) {
//get file from POST and save it in the device memory
}
...
}
推荐答案
昨晚我发现解决方案很容易上传文件....
Last night i found solution it's very easy to upload file....
首先你管理'TempFileManager'。它处理临时文件目录,因此它创建文件并在工作完成后自动删除,如复制,读取,编辑,移动等...
First you have manage 'TempFileManager'. It's handle temp file directory so it' create file and delete automatically after your work finish like copy,read,edit,move etc...
server.setTempFileManagerFactory(new ExampleManagerFactory());
所以现在你没有管理临时文件它会自动工作......
So now you not have manage temp file it's work automatically...
像这样管理发布请求
private Response POST(IHTTPSession) {
try {
Map<String, String> files = new HashMap<String, String>();
session.parseBody(files);
Set<String> keys = files.keySet();
for(String key: keys){
String name = key;
String loaction = files.get(key);
File tempfile = new File(loaction);
Files.copy(tempfile.toPath(), new File("destinamtio_path"+name).toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException | ResponseException e) {
System.out.println("i am error file upload post ");
e.printStackTrace();
}
return createResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, "ok i am ");
}
这篇关于使用NanoHttpd从POST请求中检索文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!