upload only pdf and docx file with springboot - java

I have a method that upload files, i want to accept just (pdf) and (docx) files, how i can do that.
this is the method :
#PostMapping("/upload")
public ResponseEntity<ResponseMessage> uploadFile (#RequestParam("file") MultipartFile file){
String message = "";
try {
fileService.store(file);
message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}

You can set allowed content type for endpoint:
#PostMapping("/upload", consumes = {MediaType.APPLICATION_PDF_VALUE, "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
Or you can validate file extension from input.

Other solution is to validate file extension from input as suggested by #Kryszak.
Simply add one if condition to allow pdf and docx.
For Example :
if (StringUtils.endsWithIgnoreCase(fileName, "pdf") || StringUtils.endsWithIgnoreCase(fileName, "docx")){
//process file
}
else{
// show message to user, only accept pdf & docx files.
}

Related

In email attachment any type of document file is sent with File extension instead of coreect extension

I am fetching S3 objects and then sending the object in email as an attachment. I am saving the contents in a temporary file. For images the code is working fine but in case of documents (pdf, docx, csv) files the attachments are sent without extension so they are not accessible.
try {
fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
System.out.println("fullObject: " + fullObject);
ObjectMetadata metadata = fullObject.getObjectMetadata();
System.out.println(" meta data type: " + metadata.getContentType());
InputStream inputStream = fullObject.getObjectContent();
String extension = fullObject.getKey();
int index = extension.lastIndexOf('.');
if(index > 0) {
extension = extension.substring(index + 1);
System.out.println("File extension is " + extension);
}
File file = File.createTempFile(key, "."+ extension );
System.out.println("file: "+ file);
try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(inputStream, outputStream);
} catch (Exception e) {
System.out.println("error in copying data from one file to another");
}
dataSource = new FileDataSource(file);
System.out.println("added datasource in the list");
attachmentsList.add(dataSource);
}
Upon going through this code, I got to know that the issue was not in this code but when I was setting the name of the File. I was setting filename without any extension, for example I set Filename as "temporary" this caused the documents to be saved with tmp extension. All I had to do was add the extension of the object with its name ("temporary.docx"), this solved the issue and attachments were sent properly and were accessible.

Preservring client relative path when performing multi file upload with ng-file-upload

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?

perl filehandle doesn't read file with space in its name

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

How to upload and save an attachment via XPages Java Bean

I get how you can use Expression Language to bind XPages controls to a Java Bean. Then it accesses the setters and getters automatically.
But how do you handle a file attachment?
What does that look like? I'd like to be able to I guess bind the file upload control to the bean. Save the attachment to "whatever" doc... whether it's the current or external document.. the bean should be able to handle that logic.
I guess I don't know how to get that file attachment into the in memory bean to be able to do anything with it like saving to a document.
any advice would be appreciated.
Update: This is a similar question to this: How to store uploaded file to local file system using xPages upload control?
But in that question the user wants to save to local disc. I'm looking to save to a document.
Thanks!
You need to create a getter and setter in the bean using the com.ibm.xsp.component.UIFileuploadEx.UploadedFile class:
private UploadedFile uploadedFile;
public UploadedFile getFileUpload() {
return uploadedFile;
}
public void setFileUpload( UploadedFile to ) {
this.uploadedFile = to;
}
In the function that processes the bean data (e.g. a save function) you can check if a file was uploaded by checking if the object is null. If it's not null, a file was uploaded.
To process that uploaded file, first get an instance of a com.ibm.xsp.http.IUploadedFile object using the getServerFile() method. That object has a getServerFile() method that returns a File object for the uploaded file. The problem with that object is that it has a cryptic name (probably to deal with multiple people uploading files with the same name at the same time). The original file name can be retrieved using the getClientFileName() method of the IUploadedFile class.
What I then tend to do is to rename the cryptic file to its original file name, process it (embed it in a rich text field or do something else with it) and then rename it back to its original (cryptic) name. This last step is important because only then the file is cleaned up (deleted) after the code is finished.
Here's the sample code for the steps above:
import java.io.File;
import com.ibm.xsp.component.UIFileuploadEx.UploadedFile;
import com.ibm.xsp.http.IUploadedFile;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.RichTextItem;
import com.ibm.xsp.extlib.util.ExtLibUtil; //only used here to get the current db
public void saveMyBean() {
if (uploadedFile != null ) {
//get the uploaded file
IUploadedFile iUploadedFile = uploadedFile.getUploadedFile();
//get the server file (with a cryptic filename)
File serverFile = iUploadedFile.getServerFile();
//get the original filename
String fileName = iUploadedFile.getClientFileName();
File correctedFile = new File( serverFile.getParentFile().getAbsolutePath() + File.separator + fileName );
//rename the file to its original name
boolean success = serverFile.renameTo(correctedFile);
if (success) {
//do whatever you want here with correctedFile
//example of how to embed it in a document:
Database dbCurrent = ExtLibUtil.getCurrentDatabase();
Document doc = dbCurrent.createDocument();
RichTextItem rtFiles = doc.createRichTextItem("files");
rtFiles.embedObject(lotus.domino.EmbeddedObject.EMBED_ATTACHMENT, "", correctedFile.getAbsolutePath(), null);
doc.save();
rtFiles.recycle();
doc.recycle();
//if we're done: rename it back to the original filename, so it gets cleaned up by the server
correctedFile.renameTo( iUploadedFile.getServerFile() );
}
}
}
I have code that processes an uploaded file in Java. The file is uploaded with the normal fileUpload control and then I call the following Java code from a button (that does a full refresh - so that the document including the uploaded file is saved). In the Java code you can do whatever checks you want (filename, filesize etc.):
public void importFile() {
facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
// get a handle an the uploaded file
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String fileUploadID = JSFUtil.findComponent("uploadFile").getClientId(FacesContext.getCurrentInstance());
UploadedFile uploadedFile = ((UploadedFile) request.getParameterMap().get(fileUploadID));
if (uploadedFile == null) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "No file uploaded. Use the file upload button to upload a file.", ""));
return;
}
File file = uploadedFile.getServerFile();
String fileName = uploadedFile.getClientFileName();
// Check that filename ends with .txt
if (!fileName.endsWith(".txt")) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in uploaded file. The file must end with .txt", ""));
return;
}
try {
// Open the file
BufferedReader br;
br = new BufferedReader(new FileReader(file));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// do stuff with the contents of the file
}
// Close the input stream
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in uploaded file. Please check format of file and try again", ""));
return;
}
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_INFO, "File successfully uploaded", ""));
}
With a handle on the file object you can store the file in other documents using embedObject.

How to use a save file dialog from a servlet?

I am trying to let the user save data from my servlet as a CSV file. Originally I was just locating their desktop to drop the file, but permission would be denied with this route so I want to ask the user where they want to save it.
From what I am seeing, I cannot use the Swing API in a servlet because Tomcat does not know how to draw the GUI. I tried this code:
String fileName = "ClassMonitor" + formatter.format(currentDate) + ".csv";
File csvFile = new File(fileName);
//Attempt to write as a CSV file
try{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setSelectedFile(csvFile);
int returnValue = fileChooser.showSaveDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
BufferedWriter out = new BufferedWriter(new FileWriter(csvFile));
//Iterates and writes to file
for(ClassInfo classes : csvWrite)
{
//Check if the class has a comma. Currently, only section titles have a comma in them, so that's all we check for.
classes.setSectionTitle(replaceComma(classes.getSectionTitle()));
out.write(classes.toString());
}
//Close the connection
out.close();
}
//Log the process as successful.
logger.info("File was successfully written as a CSV file to the desktop at " + new Date() + "\nFilename" +
"stored as " + fileName + ".");
}
catch(FileNotFoundException ex)
{
//Note the exception
logger.error("ERROR: I/O exception has occurred when an attempt was made to write results as a CSV file at " + new Date());
}
catch(IOException ex)
{
//Note the exception
logger.error("ERROR: Permission was denied to desktop. FileNotFoundException thrown.");
}
catch(Exception ex)
{
//Note the exception
logger.error("ERROR: Save file was not successfull. Ex: " + ex.getMessage());
}
}
But this will throw a headlessException.
Any guidance on how to implement something like a save file dialog in a servlet would be appreciated.
Just write it to the response body instead of to the local(!!) disk file system.
response.setContentType("text/csv"); // Tell browser what content type the response body represents, so that it can associate it with e.g. MS Excel, if necessary.
response.setHeader("Content-Disposition", "attachment; filename=name.csv"); // Force "Save As" dialogue.
response.getWriter().write(csvAsString); // Write CSV file to response. This will be saved in the location specified by the user.
The Content-Disposition: attachment header takes care of the Save As magic.
See also:
JSP generating Excel spreadsheet (XLS) to download
You can't call the JFileChooser from the servlet because the servlet runs on the server, not on the client; all of your Java code is executed on the server. If you want to save the file on the server, you need to already know the path you want to write to.
If you want to prompt the user's browser to save the file, use the content-disposition header: Uses of content-disposition in an HTTP response header

Categories

Resources