How to rename file in android? [duplicate] - android

This question already has answers here:
Java - removing first character of a string
(14 answers)
Closed 6 years ago.
I can apply a prefix dot (".") to all the files having .gif extension successfully. For instance, rename "my_file.gif" to ".my_file.gif"). However, I want to remove this prefix dot again using code (AKA reverse it). I have tried, but it won't work. (simply does not remove the dot) below is my code and my approach -
this is the code for adding a dot prefix(which works fine)-
// getting SDcard root path
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
walkdir(dir);
}
//detect files having these extensions and rename them
public static final String[] TARGET_EXTENSIONS = { "gif"};
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
if (fPath.endsWith(ext)) {
putDotBeforeFileName(listFile[i]);
}
}
}
}
}
}
private String putDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
int indexOfFileNameStart = fullPath.lastIndexOf(fileName);
StringBuilder sb = new StringBuilder(fullPath);
sb.insert(indexOfFileNameStart, ".");
String myRequiredFileName = sb.toString();
file.renameTo(new File(myRequiredFileName));
return myRequiredFileName;
}
}
and this is my approach for removing the dot prefix which doesn't work (no force closes)-
private String putDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
int indexOfDot = fullPath.indexOf(".");
String myRequiredFileName = "";
if (indexOfDot == 0 && fileName.length() > 1) {
myRequiredFileName = file.getParent() + "/" + fileName.substring(1);
}
try {
Runtime.getRuntime().exec(
"mv " + file.getAbsolutePath() + " " + myRequiredFileName);
} catch (IOException e) {
e.printStackTrace();
}
return myRequiredFileName;
}

Try this code
private String removeDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
String myRequiredFileName = "";
if (fileName.length() > 1 && fullPath.charAt(0)=='.') {
myRequiredFileName = file.getParent() + "/" + fileName.substring(1);
file.renameTo(new File(myRequiredFileName));
}
return myRequiredFileName;
}

Related

Speeding up the doinbackground() process

I'm splitting an encrypted video into 4 parts using this code
public class SplitVideoFile {
private static String result;
static ArrayList<String>update=new ArrayList<>();
public static String main(File file) {
try {
// File file = new File("C:/Documents/Despicable Me 2 - Trailer (HD) - YouTube.mp4");//File read from Source folder to Split.
if (file.exists()) {
String videoFileName = file.getName().substring(0, file.getName().lastIndexOf(".")); // Name of the videoFile without extension
// String path = Environment.getDataDirectory().getAbsolutePath().toString() + "/storage/emulated/0/Videointegrity";
String path = "/storage/emulated/0/Videointegrity";
// File myDir = new File(getFile, "folder");
//myDir.mkdir();
File splitFile = new File(path.concat("/").concat(videoFileName));//Destination folder to save.
if (!splitFile.exists()) {
splitFile.mkdirs();
Log.d("Directory Created -> ", splitFile.getAbsolutePath());
}
int i = 01;// Files count starts from 1
InputStream inputStream = new FileInputStream(file);
String videoFile = splitFile.getAbsolutePath() +"/"+ String.format("%02d", i) +"_"+ file.getName();// Location to save the files which are Split from the original file.
OutputStream outputStream = new FileOutputStream(videoFile);
Log.d("File Created Location: ", videoFile);
update.add("File Created Location: ".concat(videoFile));
int totalPartsToSplit =4 ;// Total files to split.
int splitSize = inputStream.available() / totalPartsToSplit;
int streamSize = 0;
int read = 0;
while ((read = inputStream.read()) != -1) {
if (splitSize == streamSize) {
if (i != totalPartsToSplit) {
i++;
String fileCount = String.format("%02d", i); // output will be 1 is 01, 2 is 02
videoFile = splitFile.getAbsolutePath() +"/"+ fileCount +"_"+ file.getName();
outputStream = new FileOutputStream(videoFile);
Log.d("File Created Location: ", videoFile);
streamSize = 0;
}
}
outputStream.write(read);
streamSize++;
}
inputStream.close();
outputStream.close();
Log.d("Total files Split ->", String.valueOf(totalPartsToSplit));
result="success";
} else {
System.err.println(file.getAbsolutePath() +" File Not Found.");
result="failed";
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public ArrayList<String> getUpdate()
{
return update;
}
And in my activity file i call this using async task's doinbackground method like below
protected String doInBackground(Void...arg0) {
Log.d(TAG + " DoINBackGround", "On doInBackground...");
File encvideo=new File(epath.getText().toString());
SplitVideoFile split=new SplitVideoFile();
String result=split.main(encvideo);
publishProgress(1);
return result;
}
Even though it splits the video, it takes too much of time to do the process.
How can I speed them up. As I'm showing a progress bar in preexecute method it looks like the user sees the progress bar for a long time, which I don't want.

How to get SD_Card path in android6.0 programmatically

I am trying to check whether device having external storage or not by using external storage path like this given below
if (new File("/ext_card/").exists()) {
specialPath = "/ext_card/";
} else if (new File("/mnt/sdcard/external_sd/").exists()) {
specialPath = "/mnt/sdcard/external_sd/";
} else if (new File("/storage/extSdCard/").exists()) {
specialPath = "/storage/extSdCard/";
} else if (new File("/mnt/extSdCard/").exists()) {
specialPath = "/mnt/extSdCard/";
} else if (new File("/mnt/sdcard/external_sd/").exists()) {
specialPath = "/mnt/sdcard/external_sd/";
} else if (new File("storage/sdcard1/").exists()) {
specialPath = "storage/sdcard1/";
}
But in marshmallow I con't find this path and while checking using ES FILEMANAGER, they give like storage/3263-3131 in Moto G 3rd generation. While check in other marshmallow devices that numbers getting differ. Please help me to check that marshmallow device have external storage or not? and if storage found means how to get the path of that external storage?
Note:- I gave permission for storage in my application and also enabled storage permission in settings for my app.
Thanks in advance and did you find any mistake in my question please crt it. thank you again.
Here's my solution, which is guaranteed to work till Android 7.0 Nougat:
/* returns external storage paths (directory of external memory card) as array of Strings */
public String[] getExternalStorageDirectories() {
List<String> results = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //Method 1 for KitKat & above
File[] externalDirs = getExternalFilesDirs(null);
String internalRoot = Environment.getExternalStorageDirectory().getAbsolutePath().toLowerCase();
for (File file : externalDirs) {
if(file==null) //solved NPE on some Lollipop devices
continue;
String path = file.getPath().split("/Android")[0];
if(path.toLowerCase().startsWith(internalRoot))
continue;
boolean addPath = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
addPath = Environment.isExternalStorageRemovable(file);
}
else{
addPath = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(file));
}
if(addPath){
results.add(path);
}
}
}
if(results.isEmpty()) { //Method 2 for all versions
// better variation of: http://stackoverflow.com/a/40123073/5002496
String output = "";
try {
final Process process = new ProcessBuilder().command("mount | grep /dev/block/vold")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
output = output + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
if(!output.trim().isEmpty()) {
String devicePoints[] = output.split("\n");
for(String voldPoint: devicePoints) {
results.add(voldPoint.split(" ")[2]);
}
}
}
//Below few lines is to remove paths which may not be external memory card, like OTG (feel free to comment them out)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < results.size(); i++) {
if (!results.get(i).toLowerCase().matches(".*[0-9a-f]{4}[-][0-9a-f]{4}")) {
Log.d(LOG_TAG, results.get(i) + " might not be extSDcard");
results.remove(i--);
}
}
} else {
for (int i = 0; i < results.size(); i++) {
if (!results.get(i).toLowerCase().contains("ext") && !results.get(i).toLowerCase().contains("sdcard")) {
Log.d(LOG_TAG, results.get(i)+" might not be extSDcard");
results.remove(i--);
}
}
}
String[] storageDirectories = new String[results.size()];
for(int i=0; i<results.size(); ++i) storageDirectories[i] = results.get(i);
return storageDirectories;
}
I found the solution for this over here https://stackoverflow.com/a/13648873/842607
The code is -
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
The other one is the hack which I found from the same page -
private static final Pattern DIR_SEPORATOR = Pattern.compile("/");
/**
* Raturns all available SD-Cards in the system (include emulated)
*
* Warning: Hack! Based on Android source code of version 4.3 (API 18)
* Because there is no standart way to get it.
* TODO: Test on future Android versions 4.4+
*
* #return paths to all available SD-Cards in the system (include emulated)
*/
public static String[] getStorageDirectories()
{
// Final set of paths
final Set<String> rv = new HashSet<String>();
// Primary physical SD-CARD (not emulated)
final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
// All Secondary SD-CARDs (all exclude primary) separated by ":"
final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
// Primary emulated SD-CARD
final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
if(TextUtils.isEmpty(rawEmulatedStorageTarget))
{
// Device has physical external storage; use plain paths.
if(TextUtils.isEmpty(rawExternalStorage))
{
// EXTERNAL_STORAGE undefined; falling back to default.
rv.add("/storage/sdcard0");
}
else
{
rv.add(rawExternalStorage);
}
}
else
{
// Device has emulated storage; external storage paths should have
// userId burned into them.
final String rawUserId;
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
{
rawUserId = "";
}
else
{
final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
final String[] folders = DIR_SEPORATOR.split(path);
final String lastFolder = folders[folders.length - 1];
boolean isDigit = false;
try
{
Integer.valueOf(lastFolder);
isDigit = true;
}
catch(NumberFormatException ignored)
{
}
rawUserId = isDigit ? lastFolder : "";
}
// /storage/emulated/0[1,2,...]
if(TextUtils.isEmpty(rawUserId))
{
rv.add(rawEmulatedStorageTarget);
}
else
{
rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
}
}
// Add all secondary storages
if(!TextUtils.isEmpty(rawSecondaryStoragesStr))
{
// All Secondary SD-CARDs splited into array
final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
return rv.toArray(new String[rv.size()]);
}
This library solve my problem.
https://github.com/hendrawd/StorageUtil
What i did is:
private File directory;
String[] allPath;
allPath = StorageUtil.getStorageDirectories(this);
for (String path: allPath){
directory = new File(path);
Methods.update_Directory_Files(directory);
}
Methods.update_Directory_Files()
// Retrieving files from memory
public static void update_Directory_Files(File directory) {
//Get all file in storage
File[] fileList = directory.listFiles();
//check storage is empty or not
if(fileList != null && fileList.length > 0)
{
for (int i=0; i<fileList.length; i++)
{
boolean restricted_directory = false;
//check file is directory or other file
if(fileList[i].isDirectory())
{
for (String path : Constant.removePath){
if (path.equals(fileList[i].getPath())) {
restricted_directory = true;
break;
}
}
if (!restricted_directory)
update_Directory_Files(fileList[i]);
}
else
{
String name = fileList[i].getName().toLowerCase();
for (String ext : Constant.videoExtensions){
//Check the type of file
if(name.endsWith(ext))
{
//first getVideoDuration
String videoDuration = Methods.getVideoDuration(fileList[i]);
long playbackPosition;
long percentage = C.TIME_UNSET;
FilesInfo.fileState state;
/*First check video already played or not. If not then state is NEW
* else load playback position and calculate percentage of it and assign it*/
//check it if already exist or not if yes then start from there else start from start position
int existIndex = -1;
for (int j = 0; j < Constant.filesPlaybackHistory.size(); j++) {
String fListName = fileList[i].getName();
String fPlaybackHisName = Constant.filesPlaybackHistory.get(j).getFileName();
if (fListName.equals(fPlaybackHisName)) {
existIndex = j;
break;
}
}
try {
if (existIndex != -1) {
//if true that means file is not new
state = FilesInfo.fileState.NOT_NEW;
//set playbackPercentage not playbackPosition
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(fileList[i].getPath());
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
retriever.release();
int duration = Integer.parseInt(time);
playbackPosition = Constant.filesPlaybackHistory.get(existIndex).getPlaybackPosition();
if (duration > 0)
percentage = 1000L * playbackPosition / duration;
else
percentage = C.TIME_UNSET;
}
else
state = FilesInfo.fileState.NEW;
//playbackPosition have value in percentage
Constant.allMemoryVideoList.add(new FilesInfo(fileList[i],
directory,videoDuration, state, percentage));
//directory portion
currentDirectory = directory.getPath();
unique_directory = true;
for(int j=0; j<directoryList.size(); j++)
{
if((directoryList.get(j).toString()).equals(currentDirectory)){
unique_directory = false;
}
}
if(unique_directory){
directoryList.add(directory);
}
//When we found extension from videoExtension array we will break it.
break;
}catch (Exception e){
e.printStackTrace();
Constant.allMemoryVideoList.add(new FilesInfo(fileList[i],
directory,videoDuration, FilesInfo.fileState.NOT_NEW, C.TIME_UNSET));
}
}
}
}
}
}
Constant.directoryList = directoryList;
}
in this i have redmi note prime 2.and i have no memory card.so when i found path and File[] externalDirs = getExternalFilesDirs(null); give null second postion value of file[].
}

renaming file extensions in android

I am able to change file extensions, for example, from ".mp4" to ".xmp4" but instead of changing extension, i simply want to add a "." before a file name for example "mikey.jpg" to ".mikey.jpg". how do i do that?
public static final String[] TARGET_EXTENSIONS = { "mp4", "mp3", "mp55", "other" };
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
fPath = fPath.replace("." + ext, ".x" + ext);
}
listFile[i].renameTo(new File(fPath));
}
}
}
}
here is the full code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (LinearLayout) findViewById(R.id.view);
// getting SDcard root path
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
walkdir(dir);
}
public static final String[] TARGET_EXTENSIONS = { "mp4", "mp3", "avi", "other" };
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
fPath = fPath.replace("." + ext, ".x" + ext);
}
listFile[i].renameTo(new File(fPath));
}
}
}
}
}
first you do String fileName = listFile[i].getName(); , which should give you the name, next you do String fullPath = listFile[i].getAbsolutePath(); to get the full path, then you do int indexOfFileNameStart = fullPath.lastIndexOf(fileName) , then you get a string builder instance from fullPath like so StringBuilder sb = new StringBuilder(fullPath); , now you call the insert method on sb sb.insert(indexOfFileNameStart, "."), now sb should have the string you desire, just construct it to string sb.toString()
Ill add this in code
private String putDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
int indexOfFileNameStart = fullPath.lastIndexOf(fileName);
StringBuilder sb = new StringBuilder(fullPath);
sb.insert(indexOfFileNameStart, ".");
String myRequiredFileName = sb.toString();
file.renameTo(new File(myRequiredFileName));
return myRequiredFileName;
}
EDIT
This is how you can use the above method in your code
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
if(fPath.endsWith(ext)) {
putDotBeforeFileName(listFile[i]);
}
}
}
}
}
}

Get path to the External SdCard in android

I want to get External SdCard path on devices if it available. by using Environment.getExternalStorageDirectory().getAbsolutePath() I can get the path to the Internal Storage. So I used below class for detecting External storage.
public class ExternalStorage {
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* #return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* #return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* #return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if(mountFile.exists()){
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if(voldFile.exists()){
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for(String mount : mMounts){
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if(list!=null){
for(File f : list){
hash += f.getName().hashCode()+":"+f.length()+", ";
}
}
hash += "]";
if(!mountHash.contains(hash)){
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if(map.isEmpty()){
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
Example usage
Map <String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard=externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);
on some device like Samsung Galaxy S3 it detects External SdCard correctly and return /storage/extSdCard for path to the External SdCard but on other devices like Sony Experia Z1 and Z2 it can't detect External Sdcard and give me the path to the Internal Storage. How can I solve this problem?
Use below code in order to get sd card path
public class DiskHelper
{
public static final int MODE_INTERNAL = 0;
public static final int MODE_EXTERNAL = 1;
public static final int MODE_EXTERNAL_SD = 2;
private StatFs statFs;
protected String path;
public DiskHelper(int mode)
{
try
{
if(mode == 0)
{
path = Environment.getRootDirectory().getAbsolutePath();
statFs = new StatFs(path);
statFs.restat(path);
}
else if(mode == 1)
{
path = Environment.getExternalStorageDirectory().getAbsolutePath();
statFs = new StatFs(path);
statFs.restat(path);
}
else
{
for(String str : getExternalMounts())
{
path = str;
statFs = new StatFs(str);
statFs.restat(str);
break;
}
}
}
catch(Exception e)
{
KLog.error(e);
}
}
public String getPath()
{
return path;
}
public long getTotalMemory()
{
if(statFs == null)
{
return 0;
}
long total = ((long)statFs.getBlockCount() * (long)statFs.getBlockSize());
return total;
}
public long getFreeMemory()
{
if(statFs == null)
{
return 0;
}
long free = ((long)statFs.getAvailableBlocks() * (long)statFs.getBlockSize());
return free;
}
public long getBusyMemory()
{
if(statFs == null)
{
return 0;
}
long total = getTotalMemory();
long free = getFreeMemory();
long busy = total - free;
return busy;
}
public static HashSet<String> getExternalMounts()
{
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try
{
final Process process = new ProcessBuilder().command("mount").redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while(is.read(buffer) != -1)
{
s = s + new String(buffer);
}
is.close();
}
catch(Exception e)
{
KLog.error(e);
}
final String[] lines = s.split("\n");
for (String line : lines)
{
if(!line.toLowerCase(Locale.US).contains("asec"))
{
if(line.matches(reg))
{
String[] parts = line.split(" ");
for(String part : parts)
{
if(part.startsWith("/"))
{
if(!part.toLowerCase(Locale.US).contains("vold"))
{
out.add(part);
}
}
}
}
}
}
return out;
}
private static final long MEGABYTE = 1024L * 1024L;
public static String humanReadableByteCount(long bytes, boolean si)
{
if(true)
{
long ret = bytes / MEGABYTE;
return ret + " MB";
}
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
Then
final DiskHelper sdDiskHelper = new DiskHelper(DiskHelper.MODE_EXTERNAL_SD);
path = sdDiskHelper.getPath();
You can customize this class.
String secStore = System.getenv("SECONDARY_STORAGE");
File externalsdpath = new File(secStore);
This will get the path of external sd secondary storage.

NanoHTTPD How to save uploaded file to sdcard folder

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...
}
In order to upload multiple files in a single input file like:
<input type="file" name="filename" multiple>
I modify decodeMultipartData() method in NanoHTTPD.java from:
private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
Map<String, String> files) throws ResponseException {
try {
int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while (mpline != null) {
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
}
boundarycount++;
Map<String, String> item = new HashMap<String, String>();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
int p = mpline.indexOf(':');
if (p != -1) {
item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
}
mpline = in.readLine();
}
if (mpline != null) {
String contentDisposition = item.get("content-disposition");
if (contentDisposition == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
}
StringTokenizer st = new StringTokenizer(contentDisposition, ";");
Map<String, String> disposition = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
int p = token.indexOf('=');
if (p != -1) {
disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
}
}
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
String value = "";
if (item.get("content-type") == null) {
while (mpline != null && !mpline.contains(boundary)) {
mpline = in.readLine();
if (mpline != null) {
int d = mpline.indexOf(boundary);
if (d == -1) {
value += mpline;
} else {
value += mpline.substring(0, d - 2);
}
}
}
} else {
if (boundarycount > bpositions.length) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
}
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
do {
mpline = in.readLine();
} while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname, value);
}
}
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
tobe:
private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
Map<String, String> files) throws ResponseException {
try {
String pname_0 = "";
String pname_1 = "";
int pcount = 1;
int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while (mpline != null) {
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
}
boundarycount++;
Map<String, String> item = new HashMap<String, String>();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
int p = mpline.indexOf(':');
if (p != -1) {
item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
}
mpline = in.readLine();
}
if (mpline != null) {
String contentDisposition = item.get("content-disposition");
if (contentDisposition == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
}
StringTokenizer st = new StringTokenizer(contentDisposition, ";");
Map<String, String> disposition = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
int p = token.indexOf('=');
if (p != -1) {
disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
}
}
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
if (pname.contentEquals(pname_0)) {
pname_1 = pname + String.valueOf(pcount);
pcount++;
} else {
pname_0 = pname;
pname_1 = pname;
}
String value = "";
if (item.get("content-type") == null) {
while (mpline != null && !mpline.contains(boundary)) {
mpline = in.readLine();
if (mpline != null) {
int d = mpline.indexOf(boundary);
if (d == -1) {
value += mpline;
} else {
value += mpline.substring(0, d - 2);
}
}
}
} else {
if (boundarycount > bpositions.length) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
}
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname_1, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
do {
mpline = in.readLine();
} while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname_1, value);
}
}
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
Hope this help and sorry for my bad English..:-)
Here's my working code:
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());
}
}
uri = uri.trim().replace(File.separatorChar, '/');
if (uri.indexOf('?') >= 0) {
uri = uri.substring(0, uri.indexOf('?'));
}
// Other implementation goes here...
if ("/uploadfiles".equalsIgnoreCase(uri)) {
String filename, tmpFilePath;
File src, dst;
for (Map.Entry entry : parms.entrySet()) {
if (entry.getKey().toString().substring(0, 8).equalsIgnoreCase("filename")) {
filename = entry.getValue().toString();
tmpFilePath = files.get(entry.getKey().toString());
dst = new File(mCurrentDir, filename);
if (dst.exists()) {
return getResponse("Internal Error: File already exist");
}
src = new File(tmpFilePath);
if (! copyFile(src, dst)) {
return getResponse("Internal Error: Uploading failed");
}
}
}
return getResponse("Success");
}
return getResponse("Error 404: File not found");
}
private boolean deleteFile(File target) {
if (target.isDirectory()) {
for (File child : target.listFiles()) {
if (! deleteFile(child)) {
return false;
}
}
}
return target.delete();
}
private boolean copyFile(File source, File target) {
if (source.isDirectory()) {
if (! target.exists()) {
if (! target.mkdir()) {
return false;
}
}
String[] children = source.list();
for (int i = 0; i < source.listFiles().length; i++) {
if (! copyFile(new File(source, children[i]), new File(target, children[i]))) {
return false;
}
}
} else {
try {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
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) {
return false;
}
}
return true;
}
private Response getResponse(String message) {
return createResponse(Response.Status.OK, MIME_PLAINTEXT, message);
}
// Announce that the file server accepts partial content requests
private Response createResponse(Response.Status status, String mimeType, String message) {
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
To allow multiple file upload:
<input type="file" name="filename" multiple>
The same issue existed in the 2.2.1 branch. Following the same logic, I fixed the same function with a few lines of code change.
Add a counter pcount at the beginning of the function:
private void decodeMultipartFormData(String boundary, String encoding, ByteBuffer fbuf, Map<String, String> parms, Map<String, String> files) throws ResponseException {
int pcount = 1;
try {
Then use the counter to update the keyname if filename is not empty:
while (matcher.find()) {
String key = matcher.group(1);
if ("name".equalsIgnoreCase(key)) {
part_name = matcher.group(2);
} else if ("filename".equalsIgnoreCase(key)) {
file_name = matcher.group(2);
// add these two line to support multiple
// files uploaded using the same field Id
if (!file_name.isEmpty()) {
if (pcount > 0)
part_name = part_name + String.valueOf(pcount++);
else
pcount++;
}
}
}
Maybe late, but just for latecommers just like me.
Explained before, the client use okhttp upload a file just like the follow code:
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
//sourceFile is a File as you know
.addFormDataPart("image_file_1", "logo-square1.png", RequestBody.create(MediaType.parse("image/png"), sourceFile))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
The follow code is what you want
#Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
// ▼ 1、parse post body ▼
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 newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
//after the body parsed, by default nanoHTTPD will save the file to cache and put it into params( "image_file_1" as key and the value is "logo-square1.png");
//files key is just like "image_file_1", and the value is nanoHTTPD's template file path in cache
// ▲ 1、parse post body ▲
// ▼ 2、copy file to target path xiaoyee ▼
Map<String, String> params = session.getParms();
for (Map.Entry<String, String> entry : params.entrySet()) {
final String paramsKey = entry.getKey();
if (paramsKey.contains("image_file_1")) {
final String tmpFilePath = files.get(paramsKey);
final String fileName = paramsKey;
final File tmpFile = new File(tmpFilePath);
final File targetFile = new File(mCurrentDir + fileName);
LogUtil.log("copy file now, source file path: %s,target file path:%s", tmpFile.getAbsoluteFile(), targetFile.getAbsoluteFile());
//a copy file method just what you like
copyFile(tmpFile, targetFile);
//maybe you should put the follow code out
return getResponse("Success");
}
}
// ▲ 2、copy file to target path xiaoyee ▲
return getResponse("Error 404: File not found");
}

Categories

Resources