I have this code where I wanted to rename the before saving it to the file system. I tried other questions here in stack overflow but it doesn't apply for me. Hoping you could help me this is my code.
#PostMapping("/api/file/upload")
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
try {
fileStorage.store(file);
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
return "Error -> message = " + e.getMessage();
}
}
This is my store function:
#Override
public void store(MultipartFile file){
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
}
I tried renaming the original file but it doesn't work.
Hoping you could help me. Thank you so much!!!
Below is working snippet with little modification here and there :
#PostMapping(value = "/api/file/upload", headers = {"content-type=multipart/*"})
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
Path TO = Paths.get("/Users/myusername/Desktop/newfileName");
try {
try {
Files.copy(file.getInputStream(), TO);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
return "Error -> message = " + e.getMessage();
}
}
OutputScreen:
Related
Download the Ghost libraries from Ghost4j site. Minimum jar required are ghost4j-1.0.0.jar, jna-3.3.0.jar, log4j-1.2.15.jar.
Also, you have to install the Ghostscript setup, which you can find from ghostscript site according to your windows bit.
Below is the code to convert the PDF to multipage TIFF.
public void PDFtoMultipageTIFFileByScript(String pdfFileLoc, String fileName, String tiffFileLoc) {
try {
Ghostscript gs = Ghostscript.getInstance();
List<String> gsArgs = new ArrayList<String>();
gsArgs.add("gswin64c.exe");
gsArgs.add("-o");
gsArgs.add(tiffFileLoc);
gsArgs.add("-sDEVICE=tiffg4");
gsArgs.add("-r600"); //Resolution.
gsArgs.add(pdfFileLoc);
//System.out.println("command running : " + gsArgs.toString());
gs.initialize(gsArgs.toArray(new String[0]));
gs.exit();
} catch (GhostscriptException e) {
System.err.println("ERROR: " + e.getMessage());
throw new RuntimeException(e.getMessage());
} catch (UnsatisfiedLinkError ule) {
throw new RuntimeException(getMessage(ule.getMessage()));
} catch (NoClassDefFoundError ncdfe) {
throw new RuntimeException(getMessage(ncdfe.getMessage()));
} catch (Exception e) {
e.printStackTrace();
}
}
String getMessage(String message) {
if (message.contains("library 'gs") || message.contains("ghost4j")) {
return message + GS_INSTALL;
}
return message;
}
I found error when filename contain with "#".
Error: java.lang.IllegalStateException: File does not exist.
But when filename without "#" still working.
String resource = "file:c:/Test#.txt";
PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
Resource[] resolveResources;
try {
resolveResources = pathResolver.getResources(resources);
if(resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resources);
}else{
for (Resource resource : resolveResources) {
if(!resource.exists()){ //true
throw new IllegalStateException("File does not exist: " + resource);
}
}
}
} catch (IOException e) {
throw new IllegalStateException("File does not exist: " + resources);
}
file names validity depends on operating system (the file system to be more accurate), so to make sure that the file can be read on any Operating system; use alphanumeric and the underscoreCharacters to avoid
in your program the problem is in the URI making function
public static void main(String[] args ){
File f = new File("ahh#.txt");
try {
if(f.createNewFile()){
System.out.println("ok"+ f.getAbsolutePath());
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// file with string path
FileInputStream fis0;
try {
fis0 = new FileInputStream(
new File(f.getAbsolutePath()));
} catch (FileNotFoundException ex) {
System.out.println("file not found with string");
}
try {
try {
// file with URI
FileInputStream fis1 =
new FileInputStream(
new File(
new URI(f.getAbsolutePath())));
} catch (URISyntaxException ex) {
System.out.println("URI???");
}
} catch (FileNotFoundException ex) {
System.out.println("file not found with URI");
}
}
It's a bit of a hack but I think you need something like this :
#Test
public void test1() {
try {
String resource = "file:c:\\tmp\\Test\u0023.txt";
PathMatchingResourcePatternResolver pathResolver = new TestPathMatchingResourcePatternResolver();
Resource[] resolveResources;
resolveResources = pathResolver.getResources(resource);
if (resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resource);
} else {
for (Resource resource2 : resolveResources) {
if (!resource2.exists()) { // true
throw new IllegalStateException("File does not exist: " + resource2);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Then you need to add modify the PathMatchingResourcePatternResolver
public class TestPathMatchingResourcePatternResolver extends PathMatchingResourcePatternResolver {
public TestPathMatchingResourcePatternResolver() {
super(new TestDefaultResourceLoader());
}
}
Then you need to modify the DefaultResourceLoader
public class TestDefaultResourceLoader extends DefaultResourceLoader {
#Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new TestUrlResource(url);
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
}
Then you need to modify the UrlResource
public class TestUrlResource extends UrlResource {
public TestUrlResource(URL url) {
super(url);
}
#Override
public boolean exists() {
return true;
}
#Override
public File getFile() throws IOException {
return new File(getURL().toString().replace("file:", ""));
}
}
So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.
Can anyone help me with example or sample? I need to get & put files on the blob storage
I have managed to code following,
try {
CloudProvider provider = (CloudProvider) Class.forName("org.dasein.cloud.azure.Azure").newInstance();
ProviderContext providerContext = new ProviderContext("DEV","West US");
//providerContext.setStorage("");
providerContext.setStorageAccountNumber("mypackages");
providerContext.setStoragePublic("XXX".getBytes());
providerContext.setEndpoint("http://XXX.blob.core.windows.net/");
providerContext.setStorageX509Key("YYY".getBytes());
provider.connect(providerContext, provider);
System.out.println("here "+provider.testContext());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
On executing above code I am getting NPE as below
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
This Works for me:
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;"
+ "AccountName=<Your accountname>;"
+ "AccountKey=<Your key>";
public static synchronized String upLoadSelected(String containername, String path, String directory, String pathPartRemover) {
List<File> filListe = new ArrayList<>();
if (storageConnectionString.isEmpty() != true) {
String respons = "";
try {
CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient serviceClient = account.createCloudBlobClient();
CloudBlobContainer container = null;
String source = "" + path;
container = serviceClient.getContainerReference("" + containername);
container.createIfNotExists();
String temp = "" + directory;
filListe = listf(source);
for (File file : filListe) {
if (file.isDirectory() == true && file.getParentFile().getName().equalsIgnoreCase(temp) != true) {
temp = (temp + "\\" + file.getName());
}
if (file.isDirectory() != true) {
CloudBlockBlob blob = container.getBlockBlobReference("" + file.getCanonicalPath().replace("" + pathPartRemover, ""));
File sourceFile = new File("" + file.getAbsolutePath());
blob.upload(new FileInputStream(sourceFile), sourceFile.length());
}
}
} catch (FileNotFoundException fileNotFoundException) {
respons = respons + "FileNotFoundException encountered: " + fileNotFoundException.getMessage();
} catch (StorageException storageException) {
respons = respons + "StorageException encountered: " + storageException.getMessage();
} catch (IOException e) {
respons = respons + "IOexception encountered: " + e.getMessage();
} catch (URISyntaxException e) {
respons = respons + "URIexception encountered: " + e.getMessage();
} catch (InvalidKeyException ex) {
respons = respons + "InvalidKeyException encountered: " + ex.getMessage();
}
return respons;
}
return "No connection";
}
public static synchronized List<File> listf(String directoryName) {
File directory = new File(directoryName);
List<File> resultList = new ArrayList<>();
File[] fList = directory.listFiles();
resultList.addAll(Arrays.asList(fList));
for (File file : fList) {
if (file.isFile()) {
} else if (file.isDirectory()) {
resultList.addAll(listf(file.getAbsolutePath()));
}
}
return resultList;
}
I am having a hard time with saving my file to my C: drive using my save button. My action listener looks like this
saveButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
File savedFile = new File("C:\\data\\inventory.dat");
if (savedFile.exists() == false)
{
try
{
savedFile.createNewFile();
outputText.append("The file has been saved\n");
}
catch (IOException ex)
{
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
if (savedFile.exists() == true)
{
try
{
savedFile.createNewFile();
outputText.append("The file already exists\n and has been overwritten\n");
}
catch (IOException ex)
{
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
);
The problem I keep running into is
Dec 06, 2013 12:14:16 AM javaguifixed.JavaGUIFixed$8 actionPerformed
SEVERE: null
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
Can anyone point me in the right direction? Why is this not saving? Essentially it should be creating the directory as well as the file if it doesn't exist and it should overwrite it if it does.
I did some playing around and got this to work. Below is my code
saveButton.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File savedFile = new File("C:\\Users\\kerinr\\Documents\\data\\inventory.dat");
if (savedFile.exists() == false) {
try {
savedFile.createNewFile();
outputText.append("The file has been saved\n");
} catch (IOException ex) {
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
if (savedFile.exists() == true) {
try {
savedFile.createNewFile();
outputText.append("The file already exists\n and has been overwritten\n");
} catch (IOException ex) {
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("C:\\Users\\kerinr\\Documents\\data\\inventory.dat"), "utf-8"));
for (int i = 0; i < inventory.size(); i++) {
writer.write(inventory.get(i).itemName + " \r\n");
writer.write(inventory.get(i).inStock + " \r\n");
writer.write(inventory.get(i).itemNumber + " \r\n");
writer.write(inventory.get(i).unitPrice + " \r\n");
writer.write(inventory.get(i).restockingFee + " \r\n");
writer.write(inventory.get(i).inventoryValue + " \r\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
});
One thing I have noticed though is that the folder "data" has to already be in place. If it is not then it will not save the file.