How to write the file from MultipartHttpServletRequest in java - java

As my backend end team will send the zip file , how to receive the file and store into the project location in java(eclipse)
As im tried some code using MultipartHttpServletRequest and getting multipart length and zip folder also created but when unable to extract that showing invalid. then how to write into the file . Please help me
#RequestMapping(value = "/retrieveBillerByFile1", method = RequestMethod.POST)
public #ResponseBody void retrieveBillerByFile1(#RequestPart MultipartHttpServletRequest request) throws Exception
{
System.out.println("RESPONSEEEE**"+request);
Iterator<String> itrator = request.getFileNames();
System.out.println("File Name:" + request.getFileNames());
MultipartFile multiFile = request.getFile(itrator.next());
System.out.println("itrator.next()" + itrator.next());
try {
// just to show that we have actually received the file
System.out.println("File Length:" + multiFile.getBytes().length);
String name = multiFile.getOriginalFilename();
System.out.println("name" + name);
System.out.println("multiFile.getBytes()" + multiFile.getBytes());
BufferedWriter w = Files.newBufferedWriter(Paths.get("D:\\cedge_uat\\" + name ));
w.write(new String(multiFile.getBytes()));
w.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("Error while loading the file");
}
}
Another Way I have tried but fileItem getting as null
#RequestMapping(value = "/retrieveBillerByFile", method = RequestMethod.POST)
public #ResponseBody void retrieveBillerByFile(#RequestPart HttpServletRequest request,
HttpServletResponse response) throws Exception
{
System.out.println("RESPONSEEEE**"+request);
System.out.println("request**"+request);
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
System.out.println("Form must has enctype=multipart/form-data.**");
// if not, we stop here
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
// sets memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(MEMORY_THRESHOLD);
// sets temporary location to store files
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// sets maximum size of upload file
upload.setFileSizeMax(MAX_FILE_SIZE);
// sets maximum size of request (include file + form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
// this path is relative to application's directory
// String uploadPath = servletContext.getRealPath("")+ File.separator + UPLOAD_DIRECTORY;
String uploadPath = servletContext.getRealPath("/WEB-INF/xml") + File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.println("uploadPath\n"+ uploadPath);
try {
// parses the request's content to extract file data
#SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
System.out.println("formItems**"+formItems);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
System.out.println("item**"+item);
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
System.out.println("fileName**"+fileName);
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
System.out.println("success");
request.setAttribute("message",
"Upload has been done successfully!");
}
}
}
} catch (Exception ex) {
System.out.println("exception"+ ex.getMessage());
request.setAttribute("message",
"There was an error: " + ex.getMessage());
}
}

You can add another param in the method --
#RequestParam MultipartFile file
so your method will be --
public #ResponseBody void retrieveBillerByFile1(#RequestParam MultipartFile file, #RequestPart MultipartHttpServletRequest request) throws Exception
And then manipulate the file using java file apis

Related

How to display uploaded images URL in browser

I am new for Multi-part in Spring Boot and I copied below code from internet for uploading files and its working fine. My requirement is after storing my files i just want to display them whenever I paste image URL in browser but using below code its getting download whenever I paste image URL.
How can I just show uploaded files instead of download?
controller
#RestController
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
#Autowired
private FileStorageService fileStorageService;
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new UploadFileResponse(fileName, fileDownloadUri,
file.getContentType(), file.getSize());
}
#GetMapping("/downloadFile/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(#PathVariable String fileName, HttpServletRequest request) {
// Load file as Resource
Resource resource = fileStorageService.loadFileAsResource(fileName);
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if(contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
Service
#Service
public class FileStorageService {
private final Path fileStorageLocation;
#Autowired
public FileStorageService(FileStorageProperties fileStorageProperties) {
this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
.toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
}
}
public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if(resource.exists()) {
return resource;
} else {
throw new MyFileNotFoundException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new MyFileNotFoundException("File not found " + fileName, ex);
}
}
}
Remove the line:
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
The Content-Disposition HTTP header usually triggers the download behavior. So you don't want to use it.

Text file is not downloading in spring mvc 3

I am able to create the file but not able to download it. I am trying to download the file by an ajax call. I am able to receive the file name and file content and successfully able to write the content in a file in application directory but I'm not able to download that file. My code is given bellow :-
The Ajax Code -:
downloadButton.onclick = function() {
//alert(payLoadID);
$.ajax({
type: "POST",
url: "payloadAjax",
data: { payloadData: document.getElementById("modal_paragraph").innerHTML, id: payLoadID },
success : function(data) {
alert("SUCCESS: " +data);
// modal.style.display = "none";
// $("body").css("overflow","auto");
},
error : function(e) {
alert("ERROR: "+ e);
},
done : function(e) {
alert("DONE");
}
})
}
Here is the java code -:
#RequestMapping(value = "/payloadAjax", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)//, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public #ResponseBody
void download(#RequestParam("payloadData") String payloadData, #RequestParam("id") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("id : " +fileName);
System.out.println("payloadData : " +payloadData);
/* File creation code is here. */
String FOLDER = "/downloadDir";
String FILE_NAME = fileName +".txt";
String appPath = request.getRealPath("");
System.out.println("appPath = " + appPath);
File downloadDirectory = new File(appPath + FOLDER);
if(!downloadDirectory.exists() || !downloadDirectory.isDirectory()) {
downloadDirectory.mkdir();
System.out.println("Directory Created");
} else {
System.out.println("Directory already exists.");
}
File uploadFile = new File(downloadDirectory, FILE_NAME);
if(uploadFile.exists()) {
uploadFile.delete();
System.out.println(uploadFile.getName() +" Has been deleted.");
}
try {
uploadFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("New File successfully created.");
try
{
PrintWriter writer = new PrintWriter(uploadFile, "UTF-8");
writer.println(payloadData);
writer.flush();
writer.close();
System.out.println("File successfully written.");
}
catch(Exception ex) {
ex.printStackTrace();
}
if (uploadFile.exists()) {
System.out.println("Upload file exists. Ready to download....");
} else {
System.out.println("Sorry File not found!!!!");
}
/*File creation code successfully completed.*/
/*File download code starts here */
/*HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_HTML);
headers.setContentLength(uploadFile.length());
headers.setContentDispositionFormData("attachment", "Soubhab_Pathak.txt");
InputStreamResource isr = new InputStreamResource(new FileInputStream(uploadFile));
return new ResponseEntity<InputStreamResource>(isr, headers, HttpStatus.OK);*/
if(response == null) {
System.out.println("Response is null.");
} else {
System.out.println("Response is not null.");
}
System.out.println("111");
OutputStream out = response.getOutputStream();
System.out.println("112");
FileInputStream in = new FileInputStream(uploadFile);
System.out.println("113");
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=" + FILE_NAME);
response.setHeader("Content-Length", uploadFile.length() +"");
FileCopyUtils.copy(in, out);
System.out.println("114");
response.flushBuffer();
System.out.println("115");
/*File download code completes here.*/
}
The log is as follows
Any idea?
Finally I am able to solve the problem. This also an example of how to download a string as file in Spring MVC using ajax. Solution is as follows -:
1) one controller action to receive the string from ajax call and store that string in a file in the application server.
2) another controller action where you need to write file download code and this action will receive a GET request.
3) in the ajax call in the success part just call the second action method to download the file.
Now the code is working fine.

Null pointer exception while trying to upload a CSV file to the server

I am trying to upload a csv file to the server. Below is my code in html:
<form method="post" id="uploadCSV" enctype="multipart/form-data">
File to upload: <input type="file" id="uploadfile" name="file" accept="text/csv">
<input type="submit" value="Upload" id="uploadcsv" ng-click="uploadCSV()"> Press here to upload the file!
</form>
And my JS:-
$scope.uploadCSV = function()
{
var fileToLoad = document.getElementById("uploadfile").files[0];
var csvreporturl = "/api/oel/csv";
$http.post(csvreporturl, fileToLoad).then(function(response, status) {
console.log("posted:",response);
});
}
Finally the controller in Spring Boot:-
#RequestMapping(value = "/api/oel/csv", method = RequestMethod.POST)
String uploadFileHandler(#RequestBody MultipartFile fileToLoad) throws FileNotFoundException, IOException
{
String name = fileToLoad.getName();
if (!fileToLoad.isEmpty()) {
try {
byte[] bytes = fileToLoad.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
File dir = new File("../dashboard-0.0.12/oel");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
return "You successfully uploaded file=" + name;
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
I am facing below error:-
Failed to load resource: the server responded with a status of 500
(HTTP/1.1 500)
Possibly unhandled rejection:
{"data":{"timestamp":1510643953084,"status":500,"error":"Internal
Server
Error","exception":"java.lang.NullPointerException","message":"No
message
available","path":"/api/oel/csv"},"status":500,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/oel/csv","data":{},"headers":{"Accept":"application/json,
text/plain,
/","Content-Type":"application/json;charset=utf-8"}},"statusText":"HTTP/1.1
500"}
Could someone please help?
Thanks
I would recommend this : Apache Commons FileUpload
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factoryItem = new DiskFileItemFactory();
ServletFileUpload uploadFile = new ServletFileUpload(factoryItem);
try {
List items = uploadFile.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}

How to create MultipartFile with location file (path)

I have location file (C:\fakepath\Code.txt) . I want to create MultipartFile with this location. My Code:
public void fileUpload(String locationFile) {
Path path = Paths.get(locationFile);
String name = "Code.txt";
String originalFileName = "Code.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile file = new MockMultipartFile(name, originalFileName, contentType, content);
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path paths = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(paths, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
Also in this code I need type my file name it's not correct for my opinion. How to create MultipartFile and save somewhere? with location
In Windows you need double slashes "C://fakepath//Code.txt"

Azure storage through java MVC web site

I have a java web app using Spring and hibernate framework. I am moving this web app on azure. In on premises web app there is one functionality in which I upload the image first in a temporary folder in C: and later access that file for application. The location of uploaded file is also stored in DB for further references. I have defined the base-path for uploading file in a properties file and accessing through it in controller as well as service layer for creating the directory, file name and file path.
Can any tell me how to do the same in azure using azure storage? Any help is appreciated.
Code in properties file:
# Base File Path for Uploading Files
fileupload.basepath=C:/webApp
Code for creating temporary folder
#RequestMapping(value = "/file/upload", method = RequestMethod.POST)
public #ResponseBody
String upload(MultipartHttpServletRequest request,
HttpServletResponse response) {
// 0. notice, we have used MultipartHttpServletRequest
// 1. get the files from the request object
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = request.getFile(itr.next());
if (!CommonUtil.isNull(mpf)) {
if (mpf.getSize() > ProductCommonConstants.MAX_FILE_UPLOAD_SIZE_IN_BYTES) {
return CommonConstants.STR_FAILURE;
}
}
long fileName = Calendar.getInstance().getTimeInMillis();
final String modelImageDirPath = baseUploadFilePath + "/"
+ CommonConstants.TEMP_FILE_NAME;
// Check for folder existence
final File modelImageDir = new File(modelImageDirPath);
if (!modelImageDir.exists()) {
// Create the directory
modelImageDir.mkdirs();
}
InputStream is = null;
FileOutputStream fos = null;
try {
String contentType = mpf.getContentType();
if (contentType != null) {
is = new DataInputStream(mpf.getInputStream());
// just temporary save file info
File file = new File(modelImageDirPath + "/" + fileName);
fos = new FileOutputStream(file);
// Write to the file
IOUtils.copy(is, fos);
}
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
} finally {
try {
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
} catch (IOException ignored) {
// Log the Exception
}
}
// 2. send it back to the client as <img> that calls get method
// we are using getTimeInMillis to avoid server cached image
return "/service/common/file/get/" + fileName;
}
}
Per my experience, you can use the upload(InputStream sourceStream, long length) of Class CloudBlob to upload files from Spring MVC MultipartFile to Azure Blob Storage, please see the code below modified from your code.
#RequestMapping(value = "/file/upload", method = RequestMethod.POST)
public #ResponseBody String upload(MultipartHttpServletRequest request,
HttpServletResponse response) {
// 0. notice, we have used MultipartHttpServletRequest
// 1. get the files from the request object
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = request.getFile(itr.next());
if (!CommonUtil.isNull(mpf)) {
if (mpf.getSize() > ProductCommonConstants.MAX_FILE_UPLOAD_SIZE_IN_BYTES) {
return CommonConstants.STR_FAILURE;
}
}
long fileName = Calendar.getInstance().getTimeInMillis();
// Modified from your code: START
String storageConnectionString = "DefaultEndpointsProtocol=http;" + "AccountName=your_storage_account;" + "AccountKey=your_storage_account_key";
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference("<blob-container-name>");
InputStream is = null;
try {
String contentType = mpf.getContentType();
if (contentType != null) {
is = new DataInputStream(mpf.getInputStream());
long length = mpf.getSize();
CloudBlockBlob blob = container.getBlockBlobReference(""+fileName);
blob.upload(is, length);
}
// Modified from your code: END
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ignored) {
// Log the Exception
}
}
// 2. send it back to the client as <img> that calls get method
// we are using getTimeInMillis to avoid server cached image
return "/service/common/file/get/" + fileName;
}
For downloading or referencing the blob, you need to record the container name & blob name of the blob to the database.
OutputStream os = ...; // get the OutputStream from the HTTP Response
CloudBlobContainer container = blobClient.getContainerReference("<container-name>");
CloudBlob blob = getBlockBlobReference("<blob-name>");
blob.download(os)
For more information, you can refer to the Javadoc of Class CloudBlob http://azure.github.io/azure-storage-java/com/microsoft/azure/storage/blob/CloudBlob.html and the Get started doc for Blob Storage https://azure.microsoft.com/en-us/documentation/articles/storage-java-how-to-use-blob-storage/.

Categories