image uploading using MultiPart - java

I am writting the code to upload a file using Spring's MultipartFile on server for that I have written following code
if(!partnersContentBean.getFile().isEmpty()){
MultipartFile file = partnersContentBean.getFile();
if(file.getOriginalFilename().endsWith(".jpeg")||file.getOriginalFilename().endsWith(".jpg")|| file.getOriginalFilename().endsWith(".gif")){
File dirPath = new File("//125.22.60.37/image/dev/cmt/");
if (!dirPath.exists()) {
dirPath.mkdirs();
}
URL url = new URL("http://125.22.60.37/image/dev/cmt/");
File destination = new File(url.toString());
file.transferTo(destination);
String url1 = request.getContextPath() + ApplicationConstants.imageUploadDirectory + file.getOriginalFilename();
System.out.println(url.getPath());
partnersContentBean.setPartnerImagename(file.getOriginalFilename());
partnersContentBean.setPartnerImagepath(destination.getPath());
}else
{
userModuleDetailBean.put("errorMessage", "File should be in type of jpg,Jpeg or GIF");
return new ModelAndView(new RedirectView("partnersAdd_CMT.htm"),"userModuleDetailBean",userModuleDetailBean);
}
}
but when I upload a file I get following exception java.io.FileNotFoundException: http:\125.22.60.37\image\dev\cmt (The filename, directory name, or volume label syntax is incorrect) dont know what path should i give to upload it

It looks like you're trying to transfer the uploaded file to another remote server (125.22.60.37). You can't do that - you can't represent an HTTP URL using a File object.
FileUpload is for storing the uploaded files to your local machine. Once there, you can worry about moving them to another remote server, but the two tasks are separate.

Related

Uploading to OpenStack Multipart With Path

I'm using java Jclouds to upload to a container inside an OpenStack Swift, the upload is going fine on the root, but when i pass a path(contains folders then the file), the file is uploaded but also creates another folder with the same name of the file. the original file name is 8mb.bin
the code is:
try {
ByteSource fileBytes = Files.asByteSource(file);
File file = new File(filePath);
String name = "test/test2/" + file.getName();
Blob blob = blobStore.blobBuilder(name)
.userMetadata(ImmutableMap.of("ContentType", contentType, "test", String.valueOf(test)))
.payload(fileBytes)
.contentLength(file.length())
.contentType(contentType)
.build();
///sednig the request
blobStore.putBlob(ContainerName, blob, multipart());
return contentLength;
}
and in the designated path its like this:
the folder 8mb.bin has the path inside it /slo/1522766773.076000/8200000/33554432 and then a file called 00000000 with the same size of the original file size.
how to solve this?
Thanks
jclouds implements Swift multipart using Static Large Objects. This has the limitation that parts exist in the same namespace as the manifest and modifying or deleting the parts invalidates the manifest. JCLOUDS-1285 suggests putting the parts in another container to clean up object listing although this requires some extra logic for deletes and overwrites.

Creating a file in linux server Java

i upload a csv file from client side and i want to create this file in server side.
Here is my function
public void uploadFile(FileUploadEvent e) throws IOException{
UploadedFile uploadedCsv=e.getFile();
String filePath="//ipAdress:/home/cg/Temp/input/ressource.csv";
byte[] bytes=null;
if(uploadedCsv != null){
bytes=uploadedCsv.getContents();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
String filename = FilenameUtils.getName(uploadedCsv.getFileName());
stream.write(bytes);
stream.close();
}
}
When I want to write the file I get this exception (No such file or directory)
SEVERE: java.io.FileNotFoundException: /ipAdress:/home/cg/Temp/input/ressource.csv (No such file or directory)
Knowing that the / home / cg / Temp / input path is created on the server.
Could you try:
String filePath="////ipAdress/home/cg/Temp/input/ressource.csv";
Instead of:
String filePath="//ipAdress:/home/cg/Temp/input/ressource.csv";
And this:
new File(new URI(filePath))
Instead of:
new File(filePath)
Or you can use jcif API How can I open a UNC path from Linux in Java?
I would use the <file>.mkdirs(); at one level above the file itself.
So do String filePath="//ipAdress:/home/cg/Temp/input
File directory = new File(filePath);
directory.mkdirs();
You can then make the file
File tempFile = new File(directory + "/ressource.csv);
Or a cleaner solution all around is just use Files.createTempFile(prefix, suffix) this will create a file in the temp directory of the system.
The reason that your code does not work is that you are trying to use a UNC pathname on Linux. Linux does not support UNC pathnames ... natively. They are a Windows-ism.
Here's your example
"//ipAdress:/home/cg/Temp/input/ressource.csv";
If you try to use that on Linux, the OS will look for a directory in the root directory of the file system. The directory it will look for will have the name ipaddress: ... noting that there is a colon in the directory name!
That will most likely fail ... because no directory with that name exists in the / directory.. And the exception message you are getting is consistent with this diagnosis.
If you are doing this because you are trying to push files out to other systems then you are going to do it some other way. For example:
Use NFS and mount the other system's file systems on the server.
Use a Java implementation of UNC names; e.g. How can I open a UNC path from Linux in Java?
(Which ever way you do it, there are security issues to consider!)
trying this new File(new URI(filePath)) instead of new File(filePath) i get this erreur. SEVERE: java.lang.IllegalArgumentException: URI is not absolute
It won't work. A UNC name is NOT a valid URL or URI.
I have found a solution for this problem, but it's not smart and still and it works
String fileName="ressource.csv";
File f = new File(System.getProperty("user.home") + "/Temp/input",fileName);
if (f.exists() && !f.canWrite())
throw new IOException("erreur " + f.getAbsolutePath());
if (!f.exists())
Files.createFile(f.toPath());
if (!f.isFile()) {
f.createNewFile(); // Exception here
} else {
f.setLastModified(System.currentTimeMillis());
}
Pending a more intelligent solution

How to upload files in resources folder in spring rest

I have a folder inside resources folder where I want to upload media files. But I am constantly getting 'No file or directory found' error.
Here is what I have in my controller
#Autowired
ServletContext servletContext;
#RequestMapping(value = "/uploads", method = RequestMethod.POST)
public String insert(#RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
// String path = new
// ClassPathResource("/src/main/resources/uploads").getPath();
// FileCopyUtils.copy(file.getBytes(), new File(path));
String webappRoot = servletContext.getRealPath("/");
String relativeFolder = File.separator + "resources" + File.separator + "uploads" + File.separator;
System.out.println(webappRoot);
System.out.println(relativeFolder);
String filename = webappRoot + relativeFolder + file.getOriginalFilename();
FileCopyUtils.copy(file.getBytes(), new File(filename));
return "uploaded successfully";
}
And here is the error I am getting constantly
SEVERE: Servlet.service() for servlet [api] in context with path [/ek-service] threw exception
java.io.FileNotFoundException: /home/ekbana/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ek-service/resources/uploads/2.jpg (No such file or directory)
I have searched all over the web tried ResourceLoader and ClassPath. But still no success figuring it out.
Resources should be considered read-only, they are not accessible through the file system, but are embedded in the war/jar when you deploy an application.
You must write the file to a path on the file system that exists and that your application has write access to.
You can write to a temporary file, it has the benefit that you most certainly will have write access to it. Useful for testing until you figure out a permanent location to store the file, or for cases when permanent storage is not necessary. See example: http://www.mkyong.com/java/how-to-create-temporary-file-in-java/

How to create a file from classpath

I'm trying to create a new file in:
project/src/resources/image.jpg
as follows:
URL url = getClass().getResource("src/image.jpg");
File file = new File(url.getPath());
but I get error:
java.io.FileNotFoundException: file:\D:\project\dist\run560971012\project.jar!\image.jpg (The filename, directory name, or volume label syntax is incorrect)
What I'm I doing wrong?
UPDATE:
I'm trying to create a MultipartFile from it:
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "image/jpeg", IOUtils.toByteArray(input));
You are not passing the image data to the file!! You're trying to write an empty file in the path of the image!!
I would recommend our Apache friends FileUtils library (getting classpath as this answer):
import org.apache.commons.io.FileUtils
URL url = getClass().getResource("src/image.jpg");
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
FileUtils.copyURLToFile(url, f);
This method downloads the url, and save it to file f.
Your issue is that "image.jpg" is a resource of your project.
As such, it's embedded in the JAR file. you can see it in the exception message :
file:\D:\project\dist\run560971012\project.jar!\image.jpg
You cannot open a file within a JAR file as a regular file.
To read this file, you must use getResourceAsStream (as detailed in this this SO question).
Good luck

Locating a file in a network disk in a Servlet

I create ImageServlet to refer to videos out of my web application scope.
The location of all of my videos are on a intranet location that could be reached from any computer in the intranet:
String path = "\\myip\storage\ogg\VX-276.ogg"
In my application, when I write it as URL - it can't display it!
If I try to open it with chrome it automatically changes it to file://myip/storage/ogg/VX-276.ogg and the file is being displayed.
I tried to do so: file:////odelyay_test64/storage/ogg/
as well but Java converts the string to: file:\myip\storage\ogg\VX-276.ogg which does not exist!
What is the correct way to refer to it?
EDITED
I create a small test:
String path = "file://myip/storage/ogg/VX-276.ogg";
File file = new File(path);
if (file.exists())
System.out.println("exists");
else {
System.out.println("missing" + file.getPath());
}
and I get:
missing file:\myip\storage\ogg\VX-276.ogg
As you can see the slashes are being switched
As per your previous question, you're referencing the resource in a HTML <video> tag. All URLs in the HTML source code must be http:// URLs (or at least be relative to a http:// URL). Most browsers namely refuse to load resources from file:// URLs when the HTML page is itself been requested by http://. You just need to let the URL point to the servlet. If the servlet's doGet() method get hit, then the URL is fine and you should not change it.
Your concrete problem is in the way how you open and read the desired file in the servlet. You need to ensure that the path in File file = new File(path) points to a valid location before you open a FileInputStream on it.
String path = "file://myip/storage/ogg/VX-276.ogg";
File file = new File(path);
// ...
If the servlet code is well written that it doesn't suppress/swallow exceptions and you have read the server logs, then you should have seen an IOException such as FileNotFoundException along with a self-explaining message in the server logs whenever reading the file fails. Go read the server logs.
Update as per the comments, it turns out that you're using Windows and thus file:// on a network disk isn't going to work for Java without mapping it on a drive letter. You need to map //myip on a drive letter first, for example X:.
String path = "X:/storage/ogg/VX-276.ogg";
File file = new File(path);
// ...
in the end I used VFS library of apache and my code looks like this:
public static void main(String[] args) {
FileSystemManager fsManager = null;
String path = "\\\\myip\\storage\\ogg\\VX-276.ogg";
try {
fsManager = VFS.getManager();
FileObject basePath;
basePath = fsManager.resolveFile("file:" + path);
if (basePath.exists())
System.out.println("exists");
else {
System.out.println("missing" + basePath.getURL());
}
} catch (FileSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this way, I don't need to create a driver for each user of the system and it allows me not to depend on operation system!

Categories