my file system
I tried to show these csv file as url but I failed
how I can get url for file in my file system?
public DownloadFileResponse downloadFile(DownloadFileRequest req) {
//TODO: create and set ImportMarketResponse object and return the following as response data
// "EventSet Id: " + req.eventSetId;
String txt ="EventSet Id: " + req.eventSetId;
DownloadFileResponse res = new DownloadFileResponse();
res.setReturnDate(txt);
return res;
}
Get url for file:
Java 7+
Paths.get("path","to","file").toUri().toURL()
Older Versions
new File(path).toURI().toURL();
Related
I am writing a file upload Spring boot application, everything except path is good to go.
I tested on Window, it works well. But when I uploaded my war package to tomcat, the upload looks successfuly. But I can't find the file on my server anywhere.
private const val UPLOADED_FOLDER = "usr/share/nginx/html/"
#PostMapping("/upload.do")
#ResponseBody
fun singleFileUpload(#RequestParam("file") file: MultipartFile,
#RequestParam("path") path: String? = "",
redirectAttributes: RedirectAttributes): ResponseEntity<*> {
if (file.isEmpty) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload")
return ResponseEntity.ok("redirect:uploadStatus")
}
val pathRoot = UPLOADED_FOLDER + path
try { // Get the file and save it somewhere
val bytes = file.bytes
val path: Path =
Paths.get(pathRoot + File.separator + file.originalFilename)
Files.write(path, bytes)
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.originalFilename + "'")
} catch (e: IOException) {
e.printStackTrace()
}
fileCompressService.decompressTar(pathRoot, file.originalFilename)
return ResponseEntity.ok("redirect:uploadStatus")
}
You use a relative path usr/share/nginx/html, which means your file is written in subdirectories of the server working directory. This might vary from server to server, but probably is $CATALINA_BASE. Use an absolute path /usr/share/nginx/html.
Remark: On a UNIX system you'll probably get permission denied, since /usr is only writable by root. Variable data should usually be written to /var.
I have a web form that I'm trying to add multi-file upload to. Currently, I can select a folder and upload multiple files. I have a Spring controller which gets the List<MultipartFile> containing all the files, resucively. However, the "original file name" includes JUST the file name. What I want is the relative path from the selected root folder, and the file name.
For example, if user uploads a directory C:\MyStuff\mypics\, I'd want to see "dog\dog1.jpg", "cat\cat5.jpg", etc. Or, "mypics\dog\dog1.jpg" would be acceptable.
HTML:
<button ngf-select="myController.uploadTest($files)"
multiple="multiple" webkitdirectory accept="image/*">Select Files ngf</button>
AngularjS Controller:
// for multiple files:
myController.uploadFiles = function (files) {
console.log("uploading files: " + files.length);
if (files && files.length) {
// send them all together for HTML5 browsers:
Upload.upload({
url: 'load-service/upload-test',
data: {file: files, myVal1: 'aaaa'},
// setting arraykey here force the data to be sent as the same key
// and resolved as a List<> in Spring Controller.
// http://stackoverflow.com/questions/35160483/empty-listmultipartfile-when-trying-to-upload-many-files-in-spring-with-ng-fil
arrayKey: ''
}).then(function (response) {
// log
}, function (response) {
// log
}, function (event) {
// log that file loaded
});
}
}
Java Spring Controller:
#PostMapping(value="upload-test")
public ResponseEntity<?> uploadTest(#RequestBody List<MultipartFile> file) {
try {
LOGGER.info("Received file set of size: " + file.size());
for (int i = 0; i < file.size(); i++) {
// testing, should be debug
MultipartFile singleFile = file.get(i);
String fileName =singleFile.getName();
String originalFileName = singleFile.getOriginalFilename();
LOGGER.info("Handling file: " + fileName);
LOGGER.info("Handling file (original): " + originalFileName);
LOGGER.info("File size: " + singleFile.getSize());
LOGGER.info("--");
}
return ResponseEntity.ok().body(new GeneralResponse("Handled file list of size: " + file.size()));
} catch (Exception ex) {
String msg = "Error getting files";
LOGGER.error(msg, ex);
return ResponseEntity.badRequest().body(new GeneralResponse(msg, ex));
}
}
I see that my controller is being called, but there's nothing I can see in teh MultipartFile objects that tell me the relative path of the files. When I debug in my browser, I can see that the files, prior to upload, have a field of webkitRelativePath attribute which has the relative path, but I don't see how to transfer that over to the server side in Spring.
Do I need to upload one file at a time and provide the relative path for each file as an optional argument to the call?
I have a few PDF files in the assets folder of a Grails 3 application. I want to load them when the user clicks some button. i.e User clicks button "Get first book", and a grails controller looks for all files in the assets folder until it finds a match, and then returns the correct one.
Currently, I am loading the files by directly accessing the path. i.e. I am using an explicit aboslute path. According to this post, this is one of the advisable approaches. However, I want to load a file in grails by asking my application to get all assets in the asset folder, instead of using any paths.
My question then is, is it possible to get all files from the assets folder in a simple manner like we can get properties in the yml file (grailsApplication.config.someProperty)
Found the solution here: Grails : getting assets local storage path inside the controller
The following sample:
def assetResourceLocator
assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
worked fine for me.
this code makes something similar for me (however, my files are located outside of my project directory). Its a controller method, that receives the file name (id) and the filetype (filetype) and looks in a predefined directory. I think you just have to adapt your "serverLocation" and "contentLocation".
To get a list of the files, which you can pass to the view:
List listOfNewsletters = []
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File f = new File(serverLocation);
if (f.exists()) {
f.eachFile() { File file ->
listOfNewsletters.push([
path: file.path,
filename: file.name,
filetype: "pdf"
])
}
}
To deliver the file:
def openNewsletter() {
if (params.id != null && params.filetype != null) {
String pdf = (String) params.id + "." + (String) params.filetype;
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File pdfFile =new File(serverLocation + pdf);
response.contentType = 'application/pdf' // or whatever content type your resources are
response.outputStream << pdfFile.getBytes()
response.outputStream.flush()
}
}
I have Successfully created folder and uploaded file in Document and Media Library.
I am storing File Name in DB and based on that file name I want to fetch that specific file from Document Library. I am new to Liferay.
I am fetching all Files saved in Document & Media Library using this Code Snippet. But is there any way to directly fetch File using File Name.
Here is my Code Snippet
public void getAllDLFileLink(ThemeDisplay themeDisplay,String folderName){
try {
Folder folder =DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
List<DLFileEntry> dlFileEntries = DLFileEntryLocalServiceUtil.getFileEntries(themeDisplay.getScopeGroupId(), folder.getFolderId());
for (DLFileEntry file : dlFileEntries) {
String url = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + themeDisplay.getScopeGroupId() + "/" +
file.getFolderId() + "/" +file.getTitle() ;
System.out.println("DL Link=>"+url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
As your code snippet already finds the URL for a DLFileEntry, I'm assuming that you want to get hold of the binary content. Check DLFileEntry.getContentStream().
If this assumption is wrong and you want to embed the image in the HTML output of your portlet, use the URL within an <img src="URL-HERE"/> tag
You can use DLFileEntryLocalServiceUtil.getFileEntry(long groupId, long folderId, java.lang.String title) to get file using file name / title, as following:
String fileName = "abc.jpg";
Folder folder = DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.getFileEntry(
themeDisplay.getScopeGroupId(), folder.getFolderId(), fileName);
However, title is stored with extension, therefore, you will require to pass complete name of image / file.
I have a java program that call my Perl script to upload a file. It has a file parameter to the Perl script that contain the location of file to upload.
public static void legacyPerlInspectionUpload(String creator, String artifactId, java.io.File uploadedFile, String description ) {
PostMethod mPost = new PostMethod(getProperty(Constants.PERL_FILE_URL) + "inspectionUpload.pl");
try {
String upsSessionId = getUpsSessionCookie();
//When passing multiple cookies as a String, seperate each cookie with a semi-colon and space
String cookies = "UPS_SESSION=" + upsSessionId;
log.debug(getCurrentUser() + " Inspection File Upload Cookies " + cookies);
Part[] parts = {
new StringPart("creator", creator),
new StringPart("artifactId", artifactId),
new StringPart("fileName", uploadedFile.getName()),
new StringPart("description", description),
new FilePart("fileContent", uploadedFile) };
mPost.setRequestEntity(new MultipartRequestEntity(parts, mPost.getParams()));
mPost.setRequestHeader("Cookie",cookies);
HttpClient httpClient = new HttpClient();
int status = httpClient.executeMethod(mPost);
if (status == HttpStatus.SC_OK) {
String tmpRetVal = mPost.getResponseBodyAsString();
log.info(getCurrentUser() + ":Inspection Upload complete, response=" + tmpRetVal);
} else {
log.info(getCurrentUser() + ":Inspection Upload failed, response=" + HttpStatus.getStatusText(status));
}
} catch (Exception ex) {
log.error(getCurrentUser() + ": Error in Inspection upload reason:" + ex.getMessage());
ex.printStackTrace();
} finally {
mPost.releaseConnection();
}
}
In this part of my Perl script, it get the information about the file, read from it and write the content to a blink file in my server.
#
# Time to upload the file onto the server in an appropropriate path.
#
$fileHandle=$obj->param('fileContent');
writeLog("fileHandle:$fileHandle");
open(OUTFILE,">$AttachFile");
while ($bytesread=read($fileHandle,$buffer,1024)) {
print OUTFILE $buffer;
}
close(OUTFILE);
writeLog("Download file, checking stats.");
#
# Find out if the file was correctly uploaded. If it was not the file size will be 0.
#
($size) = (stat($AttachFile))[7];
Right now the problem is this only work for file with no space in its name, otherwise $size is 0. I was reading online and it seems both Java file and Perl filehandle work with space, so what am I doing wrong?
Your poor variable naming has tripped you up:
open(OUTFILE,">$AttachFile");
^^^^^^^---this is your filehandle
while ($bytesread=read($fileHandle,$buffer,1024)) {
^^^^^^^^^^^--- this is just a string
You're trying to read from something that's NOT a filehandle, it's just a variable whose name happens to be "filehandle". You never opened up the specified file for reading. e.g. you're missing
open(INFILE, "<$fileHandle");
read(INFILE, $buffer, 1024);