问题描述
如何上传文件保存到SD卡的文件夹,目前它存储到/数据/数据/缓存中的文件名,如NanoHTTPD,一些随机号文件夹中。
我不能把它复制到任意文件夹的位置在SD卡。
我想将文件保存到pre提到的文件夹位置在SD卡具有相同的名称与原始文件名是从我的HTML页面上传。
我已经试过C $ CS。但文件拷贝所有类型的$失败所有的时间。1)无法获得临时文件的正确位置。2)没有得到原始文件名的形式张贴着
下面是我的实现。
请帮我停留。
公共类HttpMultimediaServer扩展NanoHTTPD {
私有静态最后字符串变量=HttpMultimediaServer;
私人的FileInputStream的FileInputStream;
公共HttpMultimediaServer(){
超(12345);
this.setTempFileManagerFactory(新ExampleManagerFactory());
}
@覆盖
市民响应服务(IHTTPSession会话){
方法方法= session.getMethod();
串的uri = session.getUri();
Log.e(处理,网址>>+ URI);
如果(uri.contains(FILESONLY)){
isfilesOnly = TRUE;
URI =/;
} 其他
isfilesOnly = FALSE;
的uri = uri.replace(%20,);
尝试 {
URI =新的String(uri.getBytes(ISO-8859-1),UTF-8);
}赶上(UnsupportedEncodingException E2){
e2.printStackTrace();
}
文件filePathServer =新的文件(URI);
如果(方法== Method.POST){
尝试 {
地图<字符串,字符串> HDRS = session.getHeaders();
地图<字符串,字符串> PARAMS = session.getParms();
地图<字符串,字符串>文件=新的HashMap<字符串,字符串>();
session.parseBody(文件);
设置<字符串>键= files.keySet();
对于(字符串键:键){
字符串名称=键;
字符串loaction = files.get(密钥);
文件临时文件=新的文件(loaction);
串tempFileName = files.get(loaction)的ToString();
文件fileToMove =新的文件(tempFileName);
通过NanoHTTPD返回//临时文件路径
串P = Environment.getExternalStorageDirectory()getPath()。
串NEWFILE = P +/LICENSE.txt;
文件NF =新的文件(NEWFILE); //我想搬到这里的文件
如果(fileToMove.canWrite()){
布尔成功= fileToMove.renameTo(NF);
如果(成功==真){
//登录到控制台
Log.i(FILE_MOVED_TO,NEWFILE);
} 其他 {
Log.e(FILE_MOVE_ERROR,tempFileName);
}
} 其他 {
Log.e(PERMISSION_ERROR_TEMP_FILE,tempFileName);
}
}
uploadstatus = UPLOAD_SUCESS;
返回新的响应(UPLOAD_SUCESS);
}赶上(例外五){
e.printStackTrace();
uploadstatus = UPLOAD_FAIL;
返回新的响应(UPLOAD_FAIL);
}
}
}
公共静态无效的复印件(SRC文件,文件DST)抛出IOException异常{
InputStream的时间=新的FileInputStream(SRC);
的OutputStream OUT =新的FileOutputStream(DST);
//传输的字节从以出
byte []的BUF =新的字节[1024];
INT LEN;
而((LEN = in.read(BUF))大于0){
out.write(BUF,0,的len);
}
附寄();
out.close();
}
公共静态无效的CopyFile(SRC文件,文件DST)抛出IOException异常
{
FileChannel随路=新的FileInputStream(SRC).getChannel();
FileChannel outChannel =新的FileOutputStream(DST).getChannel();
尝试
{
inChannel.transferTo(0,inChannel.size(),outChannel);
}
最后
{
如果(随路!= NULL)
inChannel.close();
如果(outChannel!= NULL)
outChannel.close();
}
}
私人响应getFullResponse(字符串MIMETYPE,字符串文件路径)抛出FileNotFoundException异常{
// cleanupStreams();
的FileInputStream =新的FileInputStream(文件路径);
返回新的响应(Response.Status.OK,MIMETYPE,的FileInputStream);
}
私人响应getPartialResponse(字符串MIMETYPE,字符串rangeHeader,字符串文件路径)抛出IOException异常{
档案文件=新的文件(文件路径);
字符串rangeValue = rangeHeader.trim()子。(字节=长度());
长文件长度= file.length();
长开始,结束;
如果(rangeValue.startsWith( - )){
结束=文件长度 - 1;
开始=文件长度 - 1
- 的Long.parseLong(rangeValue.substring( - 长度())。);
} 其他 {
的String []范围= rangeValue.split( - );
开始=的Long.parseLong(范围[0]);
结束= range.length> 1?的Long.parseLong(范围[1])
:文件长度 - 1;
}
如果(完>文件长度 - 1){
结束=文件长度 - 1;
}
如果(开始< =结束){
长CONTENTLENGTH =结束 - 开始+ 1;
// cleanupStreams();
的FileInputStream =新的FileInputStream(文件);
// noinspection ResultOfMethodCallIgnored
fileInputStream.skip(开始);
响应响应=新的响应(Response.Status.PARTIAL_CONTENT,MIMETYPE,的FileInputStream);
response.addHeader(内容长度,CONTENTLENGTH +);
response.addHeader(内容范围,字节+启动+ - +端+/+文件长度);
response.addHeader(内容类型,MIMETYPE);
返回响应;
} 其他 {
返回新的响应(Response.Status.RANGE_NOT_SATISFIABLE,text / html的,rangeHeader);
}
}
INT UPLOAD_SUCESS = 1;
INT UPLOAD_FAIL = -1;
INT UPLOAD_NO = 0;
INT uploadstatus;
布尔isfilesOnly;
串FILESONLY =FILESONLY = 1?;
ArrayList的< CLocalFile>清单;
StringBuilder的某人;
公共无效walkdir(文件目录){
文件的文件列表[] = dir.listFiles();
如果(的文件列表!= NULL){
的for(int i = 0; I< listFile.length;我++){
//检查是否它是一个目录
如果(listfile中[I] .isDirectory()){
如果(isfilesOnly)
walkdir(的文件列表[I]);
其他 {
CLocalFile F =新CLocalFile();
f.setName(listfile中[I] .getName());
f.setData(listfile中[I] .getAbsolutePath());
f.setSize(文件夹);
list.add(F);
继续;
}
}
//检查文件扩展名,如果它是一个文件
字符串文件名=的文件列表[I] .getName();
字符串扩展=;
INT E = fileName.lastIndexOf('。');
如果(e取代; 0){
延长= fileName.substring(E + 1);
}
如果(!isfilesOnly
|| CollabUtility.video_pattern.contains(扩展名
.toLowerCase(Locale.ENGLISH))
|| CollabUtility.document_pattern.contains(扩展名
.toLowerCase(Locale.ENGLISH))
|| CollabUtility.audio_pattern.contains(扩展名
.toLowerCase(Locale.ENGLISH))){
CLocalFile F =新CLocalFile();
f.setName(文件名);
字符串MB =字节;
双尺寸=的文件列表[I] .length();
如果(大小与GT; 1024){
大小= / 1024;
MB =KB;
}
如果(大小与GT; 1024){
大小= / 1024;
MB =MB;
}
如果(大小与GT; 1024){
大小= / 1024;
MB =国标;
}
大小= Math.floor(尺寸* 100 + 0.5)/ 100;
f.setSize(尺寸++ MB);
f.setData(listfile中[I] .getAbsolutePath());
list.add(F);
}
}
}
}
无效listofMedia(档案文件){
名单=新的ArrayList< CLocalFile>();
walkdir(文件);
现在//创建HTML页面
字符串风格=<风格>中+HTML {背景色:#eeeeee;}
+身体{背景色:#FFFFFF;
+字体家庭:宋体,宋体,黑体,无衬线;
+字体大小:18X;+边境:3PX+型槽#006600;
+填充:15px的;}+< /风格>中;
字符串脚本=< SCRIPT LANGUAGE =JavaScript的'>中
+功能clickit(州){
+如果(国家==真){的document.getElementById('FILESONLY)。检查=
+!的document.getElementById('FILESONLY)。检查}
+如果(的document.getElementById('FILESONLY)。检查== FALSE){
+变种L = window.location.href; +L = l.replace('+ FILESONLY
+',''); +了window.location =升; +}
+其他{VAR L = window.location.href;
+了window.location = String.concat(升,'+ FILESONLY +')+}
+}&所述; /脚本>中;
Log.d(检查,脚本);
SB =新的StringBuilder();
sb.append(< HTML>中);
sb.append(< HEAD>中);
sb.append(<冠军>文件来自设备< /标题>中);
sb.append(风格);
// sb.append(< SCRIPT LANGUAGE =JavaScript的'>中
// +功能clickit(){
// +如果(的document.getElementById('FILESONLY)。检查== FALSE){
// +变种L = window.location.href; +L = l.replace('+ FILESONLY
// +',''); +了window.location =升; +}
// +其他{VAR L = window.location.href;
// +了window.location = String.concat(升,'+ FILESONLY +')+}
// +}&所述; /脚本>中);
sb.append(脚本);
sb.append(< /头>);
sb.append(<身体ALINK = \蓝\虚连接= \蓝\>中);
Log.d(检查,sb.toString());
如果//(真)
// 返回;
//形式上传
sb.append(< H3>文件上传:LT; / H3>中);
sb.append(选择要上传的文件:其中; BR />中);
sb.append(<形式的行动= \\的方法= \后\是enctype = \的multipart / form-data的\>中);
sb.append(<输入类型= \文件\NAME = \一个UploadFile \大小= \50 \/>中);
sb.append(<输入类型= \提交\价值= \上传文件\/>中);
sb.append(< /形式GT;);
如果(uploadstatus == UPLOAD_FAIL)
sb.append(< H3><字体颜色='红'>将被上传失败< / FONT>< / H3>中);
否则,如果(uploadstatus == UPLOAD_SUCESS)
sb.append(< H3><字体颜色='红'>将上载是全成< / FONT>< / H3>中);
//如果文件存在与否
如果(名单= NULL和放大器;!&安培;!则为list.size()= 0){
sb.append(< H3>将以下文件从现场主持);
如果(!isfilesOnly)
sb.append(<字体颜色=蓝>中+ file.getName()
+< / FONT>将文件夹);
sb.append(下称设备< / H3>中);
} 其他 {
sb.append(< H3>找不到任何文件<字体颜色=蓝>中
+ file.getName()+&所述; /字体>将设备&lt的文件夹中; / H3>中);
}
//复选框
如果(isfilesOnly)
sb.append(<输入类型= \复选框\的onchange ='clickit(假);检查=真ID = \FILESONLY \/>中
+< ASD的onclick ='clickit(真);风格= \光标:默认; \>中
+只显示相关的文件(音频,视频和文档)< / ASD>);
其他
sb.append(<输入类型= \复选框\的onchange ='clickit(假)'ID = \FILESONLY \/>中
+< ASD的onclick ='clickit(真);风格= \光标:默认; \>中
+只显示相关的文件(音频,视频和文档)< / ASD>);
//表文件
sb.append(<表格的cellpadding =5px的'ALIGN =''>中);
//显示的URL路径,如果既文件
如果(!isfilesOnly){
ArrayList的<文件> HREF =新的ArrayList<文件>();
文件父=新的文件(file.getPath());
而(父!= NULL){
href.add(父);
//指向下一个父
父= parent.getParentFile();
}
sb.append(&其中; TR>中);
sb.append(&所述; TD列跨度= 2 - ;&其中b取代;);
sb.append(&所述; A HREF =+ file.getParent()+'>中);
sb.append(UP);
sb.append(&所述; / A>中);
//打印整个结构
字符串路径=;
对于(INT I = href.size() - 2; I> = 0; --i){
PATH = href.get(我).getPath();
如果(isfilesOnly)
路径+ = FILESONLY;
sb.append(=>&所述; A HREF =+路径+'>中);
sb.append(href.get(ⅰ).getName());
sb.append(&所述; / A>中);
}
sb.append(&所述; / B个;&所述; / TD>中);
sb.append(&所述; / TR>中);
}
sb.append(&其中; TR>中);
sb.append(&其中; TD>中);
sb.append(< B>文件名< / B>中);
sb.append(&所述; / TD>中);
sb.append(&其中; TD>中);
sb.append(< B>尺寸/类型< / B>中);
sb.append(&所述; / TD>中);
sb.append(&其中; TR>中);
//排序名单
Collections.sort(名单);
//表示的文件的列表
对于(CLocalFile F:名单){
字符串数据= f.getData();
如果(isfilesOnly)
数据+ = FILESONLY;
sb.append(&其中; TR>中);
sb.append(&其中; TD>中);
sb.append(&所述; A HREF =+数据+'>中);
sb.append(f.getName());
sb.append(&所述; / A>中);
sb.append(&所述; / TD>中);
sb.append(< TD ALIGN = \右\>中);
sb.append(f.getSize());
sb.append(&所述; / TD>中);
sb.append(&所述; / TR>中);
}
sb.append(< /表>);
sb.append(&所述; /体>中);
sb.append(< / HTML>中);
}
私有静态类ExampleManagerFactory实现TempFileManagerFactory {
@覆盖
公共TempFileManager创建(){
返回新ExampleManager();
}
}
私有静态类ExampleManager实现TempFileManager {
私人最终字符串TMPDIR;
私人最终名单,其中,临时文件>临时文件;
私人ExampleManager(){
TMPDIR = System.getProperty(java.io.tmpdir);
// TMPDIR = System.getProperty(/ SD卡);
临时文件=新的ArrayList<临时文件>();
}
@覆盖
公共临时文件createTempFile()抛出异常{
DefaultTempFile临时文件=新DefaultTempFile(TMPDIR);
tempFiles.add(临时文件);
的System.out.println(创建临时文件:+ tempFile.getName());
返回临时文件;
}
@覆盖
公共无效清除(){
如果(!tempFiles.isEmpty()){
的System.out.println(清理);
}
对于(临时文件文件:临时文件){
尝试 {
的System.out.println(+ file.getName());
file.delete();
}赶上(异常忽略){}
}
tempFiles.clear();
}
}
}
如果您使用的是NanoHTTPD r.2.1.0,请尝试以下codeS:
@覆盖
市民响应服务(IHTTPSession会话){
地图<字符串,字符串>标题= session.getHeaders();
地图<字符串,字符串> PARMS = session.getParms();
方法方法= session.getMethod();
串的uri = session.getUri();
地图<字符串,字符串>文件=新的HashMap<>();
如果(Method.POST.equals(方法)|| Method.PUT.equals(方法)){
尝试 {
session.parseBody(文件);
}赶上(IOException异常IOE){
返回GETRESPONSE(内部错误IO异常:+ ioe.getMessage());
}赶上(ResponseException重){
返回新的响应(re.getStatus(),MIME_PLAINTEXT,re.getMessage());
}
}
如果(/uploadfile".equalsIgnoreCase(uri)){
字符串文件名= parms.get(文件名);
字符串tmpFilePath = files.get(文件名);
如果(空== ||名空== tmpFilePath){
//响应的无效参数
}
文件DST =新的文件(mCurrentDir,文件名);
如果(dst.exists()){
//响应的确认覆盖
}
文件SRC =新的文件(tmpFilePath);
尝试 {
InputStream的时间=新的FileInputStream(SRC);
的OutputStream OUT =新的FileOutputStream(DST);
byte []的BUF =新的字节[65536]
INT LEN;
而((LEN = in.read(BUF))大于0){
out.write(BUF,0,的len);
}
附寄();
out.close();
}赶上(IOException异常IOE){
//响应失败
}
//响应成功
}
// 其他...
}
How to save uploaded file to sdcard folder , currently it stores to /data/data/cache folder with filename like "NanoHTTPD-some random number".
I am not able to copy it to any folder location in sdcard.
I would like to save the file to a pre-mentioned folder location in sdcard with the same name as the original file name was uploaded from my html page.
I have tried all sort of codes .But file copy fails all the time.1)Not able to get correct location of temp file.2)Not getting original filename that the form was posted with
Here is my implementation .
Please help i am stuck.
public class HttpMultimediaServer extends NanoHTTPD {
private static final String TAG = "HttpMultimediaServer";
private FileInputStream fileInputStream;
public HttpMultimediaServer() {
super(12345);
this.setTempFileManagerFactory(new ExampleManagerFactory());
}
@Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
Log.e("handle", "url>>" + uri);
if (uri.contains(filesOnly)) {
isfilesOnly = true;
uri = "/";
} else
isfilesOnly = false;
uri = uri.replace("%20", " ");
try {
uri=new String (uri.getBytes ("iso-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
File filePathServer = new File(uri);
if (method==Method.POST) {
try {
Map<String, String> hdrs=session.getHeaders();
Map<String, String> params=session.getParms();
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);
String tempFileName = files.get(loaction).toString();
File fileToMove = new File(tempFileName);
// temp file path returned by NanoHTTPD
String p =Environment.getExternalStorageDirectory().getPath();
String newFile = p + "/LICENSE.txt";
File nf = new File(newFile); // I want to move file here
if (fileToMove.canWrite()) {
boolean success = fileToMove.renameTo(nf);
if (success == true) {
// LOG to console
Log.i("FILE_MOVED_TO", newFile);
} else {
Log.e("FILE_MOVE_ERROR", tempFileName);
}
} else {
Log.e("PERMISSION_ERROR_TEMP_FILE", tempFileName);
}
}
uploadstatus = UPLOAD_SUCESS;
return new Response("UPLOAD_SUCESS");
} catch (Exception e) {
e.printStackTrace();
uploadstatus = UPLOAD_FAIL;
return new Response("UPLOAD_FAIL");
}
}
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static void copyFile(File src, File dst) throws IOException
{
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
private Response getFullResponse(String mimeType,String filePath) throws FileNotFoundException {
// cleanupStreams();
fileInputStream = new FileInputStream(filePath);
return new Response(Response.Status.OK, mimeType, fileInputStream);
}
private Response getPartialResponse(String mimeType, String rangeHeader,String filePath) throws IOException {
File file = new File(filePath);
String rangeValue = rangeHeader.trim().substring("bytes=".length());
long fileLength = file.length();
long start, end;
if (rangeValue.startsWith("-")) {
end = fileLength - 1;
start = fileLength - 1
- Long.parseLong(rangeValue.substring("-".length()));
} else {
String[] range = rangeValue.split("-");
start = Long.parseLong(range[0]);
end = range.length > 1 ? Long.parseLong(range[1])
: fileLength - 1;
}
if (end > fileLength - 1) {
end = fileLength - 1;
}
if (start <= end) {
long contentLength = end - start + 1;
// cleanupStreams();
fileInputStream = new FileInputStream(file);
//noinspection ResultOfMethodCallIgnored
fileInputStream.skip(start);
Response response = new Response(Response.Status.PARTIAL_CONTENT, mimeType, fileInputStream);
response.addHeader("Content-Length", contentLength + "");
response.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
response.addHeader("Content-Type", mimeType);
return response;
} else {
return new Response(Response.Status.RANGE_NOT_SATISFIABLE, "text/html", rangeHeader);
}
}
int UPLOAD_SUCESS = 1;
int UPLOAD_FAIL = -1;
int UPLOAD_NO = 0;
int uploadstatus;
boolean isfilesOnly;
String filesOnly = "?filesOnly=1";
ArrayList<CLocalFile> list;
StringBuilder sb;
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
// checking if it is a directory
if (listFile[i].isDirectory()) {
if (isfilesOnly)
walkdir(listFile[i]);
else {
CLocalFile f = new CLocalFile();
f.setName(listFile[i].getName());
f.setData(listFile[i].getAbsolutePath());
f.setSize("Folder");
list.add(f);
continue;
}
}
// checking the file extension if it is a file
String fileName = listFile[i].getName();
String extension = "";
int e = fileName.lastIndexOf('.');
if (e > 0) {
extension = fileName.substring(e + 1);
}
if (!isfilesOnly
|| CollabUtility.video_pattern.contains(extension
.toLowerCase(Locale.ENGLISH))
|| CollabUtility.document_pattern.contains(extension
.toLowerCase(Locale.ENGLISH))
|| CollabUtility.audio_pattern.contains(extension
.toLowerCase(Locale.ENGLISH))) {
CLocalFile f = new CLocalFile();
f.setName(fileName);
String mb = "Bytes";
double size = listFile[i].length();
if (size > 1024) {
size = size / 1024;
mb = "KB";
}
if (size > 1024) {
size = size / 1024;
mb = "MB";
}
if (size > 1024) {
size = size / 1024;
mb = "GB";
}
size = Math.floor(size * 100 + 0.5) / 100;
f.setSize(size + " " + mb);
f.setData(listFile[i].getAbsolutePath());
list.add(f);
}
}
}
}
void listofMedia(File file) {
list = new ArrayList<CLocalFile>();
walkdir(file);
// now create the html page
String style = "<style>" + "html {background-color:#eeeeee;} "
+ "body { background-color:#FFFFFF; "
+ "font-family:Tahoma,Arial,Helvetica,sans-serif; "
+ "font-size:18x; " + "border:3px " + "groove #006600; "
+ "padding:15px; } " + "</style>";
String script = "<script language='javascript'>"
+ "function clickit(state) {"
+ "if(state==true){document.getElementById('filesonly').checked="
+ "! document.getElementById('filesonly').checked}"
+ "if ( document.getElementById('filesonly').checked == false ){"
+ "var l=window.location.href;" + "l=l.replace('" + filesOnly
+ "', '');" + "window.location=l;" + "}"
+ "else{var l=window.location.href;"
+ "window.location=String.concat(l,'" + filesOnly + "')" + "}"
+ "}</script>";
Log.d("check", script);
sb = new StringBuilder();
sb.append("<html>");
sb.append("<head>");
sb.append("<title>Files from device</title>");
sb.append(style);
// sb.append("<script language='javascript'>"
// + "function clickit() {"
// + "if ( document.getElementById('filesonly').checked == false ){"
// + "var l=window.location.href;" + "l=l.replace('" + filesOnly
// + "', '');" + "window.location=l;" + "}"
// + "else{var l=window.location.href;"
// + "window.location=String.concat(l,'" + filesOnly + "')" + "}"
// + "}</script>");
sb.append(script);
sb.append("</head>");
sb.append("<body alink=\"blue\" vlink=\"blue\">");
Log.d("check", sb.toString());
// if(true)
// return;
// form upload
sb.append("<h3>File Upload:</h3>");
sb.append("Select a file to upload: <br/>");
sb.append("<form action=\"\" method=\"post\" enctype=\"multipart/form-data\">");
sb.append("<input type=\"file\" name=\"uploadfile\" size=\"50\" />");
sb.append("<input type=\"submit\" value=\"Upload File\" />");
sb.append("</form>");
if (uploadstatus == UPLOAD_FAIL)
sb.append("<h3><font color='red'>The upload was failed</font></h3>");
else if (uploadstatus == UPLOAD_SUCESS)
sb.append("<h3><font color='red'>The upload was successfull</font></h3>");
// if files are there or not
if (list != null && list.size() != 0) {
sb.append("<h3>The following files are hosted live from ");
if (!isfilesOnly)
sb.append("<font color='blue'>" + file.getName()
+ "</font> folder of ");
sb.append("the device</h3>");
} else {
sb.append("<h3>Couldn't find any file from <font color='blue'>"
+ file.getName() + "</font> folder of the device</h3>");
}
// checkbox
if (isfilesOnly)
sb.append("<input type=\"checkbox\" onchange='clickit(false);' checked='true' id=\"filesonly\" />"
+ "<asd onclick='clickit(true);' style=\"cursor:default;\">"
+ "Show only relevant Files (Audio, Video and Documents)</asd>");
else
sb.append("<input type=\"checkbox\" onchange='clickit(false);' id=\"filesonly\" />"
+ "<asd onclick='clickit(true);' style=\"cursor:default;\">"
+ "Show only relevant Files (Audio, Video and Documents)</asd>");
// table of files
sb.append("<table cellpadding='5px' align=''>");
// showing path URLs if not only files
if (!isfilesOnly) {
ArrayList<File> href = new ArrayList<File>();
File parent = new File(file.getPath());
while (parent != null) {
href.add(parent);
// pointing to the next parent
parent = parent.getParentFile();
}
sb.append("<tr>");
sb.append("<td colspan=2><b>");
sb.append("<a href='" + file.getParent() + "'>");
sb.append("UP");
sb.append("</a>");
// printing the whole structure
String path = "";
for (int i = href.size() - 2; i >= 0; --i) {
path = href.get(i).getPath();
if (isfilesOnly)
path += filesOnly;
sb.append(" => <a href='" + path + "'>");
sb.append(href.get(i).getName());
sb.append("</a>");
}
sb.append("</b></td>");
sb.append("</tr>");
}
sb.append("<tr>");
sb.append("<td>");
sb.append("<b>File Name</b>");
sb.append("</td>");
sb.append("<td>");
sb.append("<b>Size / Type</b>");
sb.append("</td>");
sb.append("<tr>");
// sorting the list
Collections.sort(list);
// showing the list of files
for (CLocalFile f : list) {
String data = f.getData();
if (isfilesOnly)
data += filesOnly;
sb.append("<tr>");
sb.append("<td>");
sb.append("<a href='" + data + "'>");
sb.append(f.getName());
sb.append("</a>");
sb.append("</td>");
sb.append("<td align=\"right\">");
sb.append(f.getSize());
sb.append("</td>");
sb.append("</tr>");
}
sb.append("</table>");
sb.append("</body>");
sb.append("</html>");
}
private static class ExampleManagerFactory implements TempFileManagerFactory {
@Override
public TempFileManager create() {
return new ExampleManager();
}
}
private static class ExampleManager implements TempFileManager {
private final String tmpdir;
private final List<TempFile> tempFiles;
private ExampleManager() {
tmpdir = System.getProperty("java.io.tmpdir");
// tmpdir = System.getProperty("/sdcard");
tempFiles = new ArrayList<TempFile>();
}
@Override
public TempFile createTempFile() throws Exception {
DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
tempFiles.add(tempFile);
System.out.println("Created tempFile: " + tempFile.getName());
return tempFile;
}
@Override
public void clear() {
if (!tempFiles.isEmpty()) {
System.out.println("Cleaning up:");
}
for (TempFile file : tempFiles) {
try {
System.out.println(" "+file.getName());
file.delete();
} catch (Exception ignored) {}
}
tempFiles.clear();
}
}
}
If you are using NanoHTTPD r.2.1.0, please try these codes:
@Override
public Response serve(IHTTPSession session) {
Map<String, String> headers = session.getHeaders();
Map<String, String> parms = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
Map<String, String> files = new HashMap<>();
if (Method.POST.equals(method) || Method.PUT.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return getResponse("Internal Error IO Exception: " + ioe.getMessage());
} catch (ResponseException re) {
return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
if ("/uploadfile".equalsIgnoreCase(uri)) {
String filename = parms.get("filename");
String tmpFilePath = files.get("filename");
if (null == filename || null == tmpFilePath) {
// Response for invalid parameters
}
File dst = new File(mCurrentDir, filename);
if (dst.exists()) {
// Response for confirm to overwrite
}
File src = new File(tmpFilePath);
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[65536];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ioe) {
// Response for failed
}
// Response for success
}
// Others...
}
这篇关于NanoHTTPD如何保存上传的文件到SD卡的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!