How to upload image file to spring mvc resource folder - java

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));

Related

Can anyone please explain how the Spring's Multipartfile works?

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;
}

How to unzip zip file in JCIFS

I have zip file on remote server, which I am accessing using JCIFS. I want to extract contents of that zip on remote server only. tried :
private void unzipFile(SmbFile zipFile) {
try {
String destPath = "//SHARED-PC/reports/";
int BUFFER_SIZE = 4096;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipFile.getInputStream().read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}catch(Exception e) {
logger.error(" Error while unzipping zip file "+zipFile+" "+zipFile.getName());
e.printStackTrace();
}
}
But its alwayts reslting in errors
1. Access is Denied
2. I changed given path of dest folder - (The filename, directory name, or volume label syntax is incorrect)
Can someone suggest how it can be done? Thanx in advance
Update:
As per Petesh suggestion I used ZipInputStream to extract files from zip file.
i tried :
private static void unzip(SmbFile zipFilePath, String destDir) throws SmbException {
System.out.println(" Unzipping :: "+zipFilePath); //smb://WIN-B3TN6C0DC94/My_daily_reports/19-5-2018/Success/100-Sales-Records-19-5-2018.zip
System.out.println(" destdir is :: "+destDir); // smb://WIN-B3TN6C0DC94/My_daily_reports/19-5-2018/Success/
try {
ZipInputStream zis = new ZipInputStream(zipFilePath.getInputStream());
ZipEntry ze = zis.getNextEntry();
String fileName = ze.getName();
File newFile = new File(destDir);
System.out.println("newfile Path : "+newFile.getPath());
byte[] buf = new byte[1024];
String outputFilepathAndName = newFile.getPath() + File.separator + fileName;
System.out.println("outputFilepathAndName :: "+outputFilepathAndName);
OutputStream outputStream = new FileOutputStream(fileName);
while(ze != null){
int length;
while((length = zis.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
}
System.out.println("Write done // flushing now... ");
zis.closeEntry();
zis.close();
outputStream.close();
System.out.println(" UNZIP SUCCESSFUL "+fileName);
} catch (Exception e) {
System.out.println(" UNZIP ERROR");
e.printStackTrace();
}
}
But it gets stuck in while loop. Can anyone suggest what is going wrong here. I tried using OutputStream and BufferedOutputStream as well.

FileOutPutStream not creating the filepath

private byte[] convertStreamToBytes(InputStream inputStream){
FileOutputStream out = null;
try {
String filename = DataUtil.hashFilename(getDocumentUri(), getFileName());
String filePath = Environment.getExternalStorageDirectory().getPath() + AESConstants.APOLLO_DOWNLOADS_NC_DIR;
//String path = context.getFilesDir() + folder;
File dir = new File(filePath);
dir.mkdirs();
filePath += filename;
File file = new File(filePath);{
AESLog.log(TAG, "filePath:: "+filePath);
if(file.exists()){
AESLog.log(TAG, "File Exist :: "+filePath);
boolean deleteStatus = file.delete();
AESLog.log(TAG, "deleteStatus:: "+deleteStatus);
}
}
if (inputStream == null)
throw new RuntimeException("stream is null");
out = new FileOutputStream(file);
byte buf[] = new byte[128];
do {
int numread = inputStream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
out.close();
//inputStream.close();
} catch (IOException ex) {
}finally{
try{
if(null != inputStream){
out.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
I am getting all file from an Api, the code above is to create a filepath and save the file in that particular path.
It was working fine until now. Issue happening when creating a filepath like "/storage/sdcard0/apollodownloads/nc/852945139"First.py".rtf" this. FileOutStream object null returning when creating this path. Whats the issue happening?
You need to escape your path, when it has special symbols , like " in your case
Escape the path something like this:
"/storage/sdcard0/apollodownloads/nc/852945139\"First.py\".rtf";
Details about escaping can be found here

Error while opening the generated PDF file with Servlets

By using the following code a PDF file is getting opened, I simply write the file to the servlet's output stream, but, when i am trying to open that PDF file it showing an error : "Not a pdf or Corrupted"
My code:
public void displayPj() {
String url = ficheToDisplay.getUrl();
String outPutFile = ficheToDisplay.getNom();
HttpServletResponse resp = null;
resp = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
File file = new File(url);
resp.reset();
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ outPutFile + "\"");
resp.setContentType("application/pdf;charset=UTF-8");
resp.setHeader("Content-Length", String.valueOf(file.length()));
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
ServletOutputStream outStream = resp.getOutputStream();
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(resp.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
outStream.close();
} catch (Exception e) {
System.err
.println("PROBLEM STREAMING DAILY REPORT PDF THROUGH RESPONSE!"
+ e);
e.printStackTrace();
FacesMessage fm = new FacesMessage("Could Not Retrieve PDF.");
FacesContext.getCurrentInstance().addMessage(
"dailyReportArchiveFailure", fm);
}
FacesContext.getCurrentInstance().responseComplete();
}

File upload from another computer

I have a problem regarding on uploading a file. When I upload the files myself(localhost) it actually works but when I let other people in the same network upload their file it gives me an error:
(The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at sources.UploadAIP.actions.uploadAction.processRequest(uploadAction.java:49)
Here is my actual code:
public class uploadAction extends AbstractAppAction
{
public boolean processRequest(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response)
{
try{
Properties appProperties = getAppProperties();
String dbMap = appProperties.getProperty("dbMap");
DB db = getDBConnection(dbMap);
String myDirectory = "C:\\tmp";
String uploadedFile = request.getParameter("filename");
System.out.println("srcfile: " +myDirectory);
System.out.println("file: " +uploadedFile);
String errorMessage = "";
ServletContext sc = servlet.getServletContext();
String fileName = StringUtil.stringReplace(uploadedFile,"\\","\\");
int i = fileName.lastIndexOf("\\");
if (i > 0) {
fileName = fileName.substring(i+1);
}
File srcFile = new File(uploadedFile);
File targetDirectory = new File(myDirectory);
String dirname = StringUtil.stringReplace(targetDirectory.toString() ,"\\","\\");
System.out.println("directory name:" +dirname);
File destFile = new File(dirname+"\\"+fileName);
System.out.println(destFile);
System.out.println("here is the parent directory: " +targetDirectory);
if(!targetDirectory.exists()){
targetDirectory.mkdirs();
}
InputStream inStream;
OutputStream outStream;
try{
inStream = new FileInputStream(srcFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
fileName = StringUtil.stringReplace(uploadedFile, "\\", "\\");
int u = fileName.lastIndexOf("\\");
if (u > 0)
{
fileName = fileName.substring(i + 1);
}
if (!dirname.endsWith("\\"))
{
dirname = dirname + "\\";
}
File f = new File(dirname);
String uploadDir = dirname;
System.out.println("uploadDirectory" +uploadDir);
} catch (Exception ex) {
request.setAttribute("message", ex.toString());
ex.printStackTrace();
}
return (true);
}
}
Your code assumes that the file being uploaded is present on the same local machine, which isnt true, since you are receiving uploads from a local network.
This is why it works on your local machine, but not across a network.
To upload a file, you need a multipart form and a servlet that correctly handles a multipart request.
This tutorial should help you:
http://www.avajava.com/tutorials/lessons/how-do-i-upload-a-file-to-a-servlet.html

Categories