i've been trying to understand how the multipartfile works in spring
but did't find out any helpful info on internet.
Trying to understand this method:
public String copyUploadedImage(MultipartFile multipartFile, String realpath, int userId) throws IOException {
String orgFileName = null;
orgFileName = multipartFile.getOriginalFilename();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
String root = realpath + File.separator + userId + File.separator + "Image" + File.separator;
File file = new File(root + File.separator);
if (file.mkdirs()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
fileName = file + File.separator + multipartFile.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
return orgFileName;
}
Related
I am building a library for android, and it requires me to unzip files. It works on every single other file except for one file in one particular archive. I get a file not found exception on this. I am not a java expert, or an android expert, but my team is also stumped. Just hoping someone can spot something in my code that could be creating a bug.
public static void unzip(File zipFile,
String unzipFilePath,
FetchInterface responseHandler,
JSONObject json) {
final int BUFFER_SIZE = 4096;
String filename;
InputStream inputStream;
ZipInputStream zipInputStream;
ZipEntry zipEntry = null;
String path = unzipFilePath + File.separator;
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
String zipRootDirectory = null;
inputStream = new FileInputStream(zipFile);
zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
byte[] buffer = new byte[BUFFER_SIZE];
int count;
// Log.d(tag, zipFile.getName());
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
filename = zipEntry.getName();
Log.d(tag, "ZIP ENTRY: " + zipEntry.getName());
if (zipRootDirectory == null) {
zipRootDirectory = zipEntry.getName().split("\\/")[0];
// Log.d(tag, "ROOT DIR: " + zipRootDirectory);
}
if (zipEntry.isDirectory()) {
Log.d(tag, "ZIPENTRY IS DIR: " + zipEntry.toString());
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
try {
FileOutputStream fout = new FileOutputStream(path + filename);
Log.e(tag, "FILENAME: " + filename);
while ((count = zipInputStream.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
} catch(FileNotFoundException e) {
Log.e(tag, "ERROR AT THIS FILE: " + filename);
e.printStackTrace();
}
zipInputStream.closeEntry();
}
zipInputStream.close();
File zipRootDirectoryFile = new File(path + File.separator + zipRootDirectory);
if (zipRootDirectoryFile.exists()) {
Log.d(tag, zipRootDirectoryFile.getName());
File renameFile = new File(path + File.separator + "html" + File.separator);
zipRootDirectoryFile.renameTo(renameFile);
} else {
Log.e(tag, "directory cannot be renamed as it does not exist");
}
} catch (IOException e) {
e.getStackTrace();
}
}
im working on a spring mvc project . i want to upload image and save it to resources/img/folder.
I tried below code but it does not save the image to the directory.
#Autowired
private HttpServletRequest request;
try {
// MultipartFile file = uploadItem.getFileData();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
System.out.println("File Size:::" + multipartFile.getSize());
fileName = request.getSession().getServletContext().getRealPath("/resources/") + "/students/"
+ multipartFile.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("OriginalFilename:" + multipartFile.getOriginalFilename());
System.out.println("fileName----"+fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Exception
11:00:39,436 INFO [stdout] (http--0.0.0.0-8080-5) File Size:::7346
11:00:39,436 ERROR [stderr] (http--0.0.0.0-8080-5) java.io.FileNotFoundException
: C:\jboss-as-7.1.1.Final\standalone\tmp\vfs\deployment65ea7dd580659db3\ObviousR
esponseWeb-1.2-SNAPSHOT.war-3a7509e73dad1cba\resources\students\zzzz.jpg (The sy
stem cannot find the path specified)
String saveDirectory=request.getSession().getServletContext().getRealPath("/")+"images\\";//to save to images folder
String fileName = multipartFile.getOriginalFilename();//getting file name
System.out.println("directory with file name: " + saveDirectory+fileName);
multipartFile.transferTo(new File(saveDirectory + fileName));
I have implemented the download of files. It is downloading and saving it to memory.
Now my problem is, if there is folder and sub folder, I need to ZIP the folder and download the zip file and save it in memory. I tried lot but I did'nt find a solution. Can any one can guide me to get the solution?
Here my download single file code...
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
ZipOutputStream zos = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP "
+ connection.getResponseCode() + " "
+ connection.getResponseMessage();
}
String fileName = tvtitle.getText().toString();
String fileExtension = tvtype.getText().toString();
File imageDirectory = new File(Path);
imageDirectory.mkdirs();
int fileLength = connection.getContentLength();
String _path = Path;
input = connection.getInputStream();
File outputFile = new File(_path, fileName + fileExtension);
output = new FileOutputStream(outputFile);
// zos = new ZipOutputStream(output);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
first add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
call this method by passing "inputFolderPath" and "outputFolderPath"
private static void zipFolder(String inputFolderPath, String outZipPath) {
try {
FileOutputStream fos = new FileOutputStream(outZipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(inputFolderPath);
File[] files = srcFile.listFiles();
Log.d("", "Zip directory: " + srcFile.getName());
for (int i = 0; i < files.length; i++) {
Log.d("", "Adding file: " + files[i].getName());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
zos.close();
} catch (IOException ioe) {
Log.e("", ioe.getMessage());
}
}
My file unzips one folder and one file but does not unzip the rest for some reason. How can I make it so it unzips all of the zip files contents?
public void unzip(String filepath, String filename, String unzip_path) throws IOException {
InputStream is = new FileInputStream(filepath + filename);
Log.d("1st", filepath + filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
String filename_temp = ze.getName();
File fmd = new File(unzip_path + filename_temp);
Log.d("2nd", unzip_path + filename_temp);
if (!fmd.getParentFile().exists()) {
fmd.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(unzip_path + filename_temp);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
//}
}
} finally {
zis.close();
}
}
I used the following code to zip my files and it works great but I would like to zip only the subfolders and not have the root of the tree show up in the zip file.
public boolean zipFileAtPath(String sourcePath, String toLocation) {
// ArrayList<String> contentList = new ArrayList<String>();
File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
File[] fileList = folder.listFiles();
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(out, file, basePathLength);
} else {
byte data[] = new byte[BUFFER];
String unmodifiedFilePath = file.getPath();
String relativePath = unmodifiedFilePath
.substring(basePathLength);
Log.i("ZIP SUBFOLDER", "Relative Path : " + relativePath);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}
public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
Right now if I enter Environment.getExternalStorageDirectory().toString()+"/X123" as the sourcePath X123 is included in the tree.
-ZipFile
-X123
-SubFolder1
-SubFolder2
-...
I would like to remove X123
-ZipFile
-SubFolder1
-SubFolder2
-...
Thank you
Played around and ended up using the following code:
static public void zipFolder(String srcFolder, String destZipFile)
throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path.replace("X123/", "") + "/" + folder.getName()));
//zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static private void addFolderToZip(String path, String srcFolder,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
+ fileName, zip);
}
}
}