Check if Spring Multipart File uploaded has a form field - spring

We were using the apache file uploads for uploading a file and below code was used for the same.
ServletFileUpload upload = new ServletFileUpload(itemFactory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
conf.put(name, value);
} else {
InputStream is = item.getInputStream();
byte[] bytes = ByteStreams.toByteArray(is);
String query = new String(bytes, "UTF-8");
conf.put("test", query);
}
}
But we recently moved to Spring boot and trying to use spring multipart to upload a file.The code which will replace the above code will be
DefaultMultipartHttpServletRequest requestMain = (DefaultMultipartHttpServletRequest) request;
Iterator<String> fileNameIterator = requestMain.getFileNames();
ListIterator<MultipartFile> iterator = null;
while (fileNameIterator.hasNext()) {
multipartFiles = requestMain.getFiles(fileNameIterator.next());
iterator = multipartFiles.listIterator();
while (iterator.hasNext()) {
MultipartFile item = iterator.next();
if (item.isEmpty()) {
// String name = item.getFieldName();
// String value = item.getString();
// conf.put(name, value);
} else {
InputStream is = item.getInputStream();
byte[] bytes = ByteStreams.toByteArray(is);
String query = new String(bytes, "UTF-8");
conf.put("query", query);
}
}
}
But I am not able to figure out how to check if the file has a form field in spring boot.In apache file upload it was achieved using item.isFormField() method.

You don't need to check if the item is form field.
The requestMain.getFiles(fileNameIterator.next()); method will return a MultipartFile so you know is not a form field.
To get the form fields use
requestMain.getParameterMap()
Or, for a specific field use
requestMain.getParameter("field")

Related

Spring Boot - Handle CSV as well as Excel Multipart file

I have a REST API in Spring Boot Application that takes in a param of type Multipart file.
There is possibility that user may import either CSV file or Excel(.xlsx / .xsl) file of huge size which needs to be handled.
I am using Apache POI to read Excel type file and it is working fine. To my existing code, how do I efficiently handle CSV file reading also
Below is Excel file Reading Code:
#RequestMapping(value="/read", method = RequestMethod.POST)
#Transactional
public Map<String, String> read(#RequestParam("file") MultipartFile file) {
Map<String, String> response = new ArrayList();
if (!file.isEmpty()) {
ByteArrayInputStream stream;
Workbook wb;
StringBuilder contentSb = new StringBuilder();
try {
stream = new ByteArrayInputStream(file.getBytes());
wb = WorkbookFactory.create(stream);
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
Iterator<Row> rowIterator = sheet.rowIterator();
System.out.println("Processing Excel file");
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row != null) {
Cell cell = row.getCell(0);
if (cell != null) {
contentSb.append(cell.getStringCellValue()+",");
}
}
}
System.out.println("Processed Excel file");
return response;
} catch (Exception e) {
e.printStackTrace();
}
}
else {
return response;
}
}
Thank you in advance!

JSON input for Upload function in WebApi C#

I have an upload function in my WebApi C# code, which works fine with Query string parameters. I will be passing the file in Rest client using multi-Form data and it works completely fine.
Now I have to change the parameters to JSON format, doing so the request is not hitting the controller. Can anyone please help me here.
public ReturnMsg UploadDocument(string fileName, string fileSize, string ApplNo, string DocId, string DocSize,string resumeId,string DependId)
{
ReturnMsg objReturnMsg = new ReturnMsg ();
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
Stream stream = null;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = string.Empty;
stream = postedFile.InputStream;
}
objReturnMsg = Bll.UploadFiles(fileName, fileSize, DocId, DocSize,DependId,stream);
}
else
{
objReturnMsg.Status = "F";
objReturnMsg.ReturnMessage = "Please Upload a Valid Form";
}
return objReturnMsg;
}
I want it in
public ReturnMsg UploadDocument(DocDetails docDet)
{
ReturnMsg objReturnMsg = new ReturnMsg ();
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
Stream stream = null;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = string.Empty;
stream = postedFile.InputStream;
}
objReturnMsg = Bll.UploadFiles(docDet.fileName, docDet.fileSize, docDet.DocId, docDet.DocSize,docDet.DependId,stream);
}
else
{
objReturnMsg.Status = "F";
objReturnMsg.ReturnMessage = "Please Upload a Valid Form";
}
return objReturnMsg;
}

Spring mvc When using enctype="multipart/form-data" modelAttribute values equal null in the controller

I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}

MVC 6 HttpPostedFileBase?

I am attempting to upload an image using MVC 6; however, I am not able to find the class HttpPostedFileBase. I have checked the GitHub and did not have any luck. Does anyone know the correct way to upload a file in MVC6?
MVC 6 used another mechanism to upload files. You can get more examples on GitHub or other sources. Just use IFormFile as a parameter of your action or a collection of files or IFormFileCollection if you want upload few files in the same time:
public async Task<IActionResult> UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName;
}
...
}
[HttpPost]
public async Task<IActionResult> UploadMultiple(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath,"uploads");
foreach(var file in files)
{
if(file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads,fileName));
}
...
}
}
You can see current contract of IFormFile in asp.net sources. See also ContentDispositionHeaderValue for additional file info.
There is no HttpPostedFileBase in MVC6. You can use IFormFile instead.
Example: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs
Snippet from the above link:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
I was searching around for quite a while trying to piece this together in .net core and ended up with the below. The Base64 conversion will be next to be done so that the retrieval and display is a little easier. I have used IFormFileCollection to be able to do multiple files.
[HttpPost]
public async Task<IActionResult> Create(IFormFileCollection files)
{
Models.File fileIn = new Models.File();
if(model != null && files != null)
{
foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
byte[] fileBytes = null;
using (var fileStream = file.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
//string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
fileIn.Filename = fileName;
fileIn.FileLength = Convert.ToInt32(file.Length);
fileIn.FileType = file.ContentType;
fileIn.FileTypeId = model.FileTypeId;
fileIn.FileData = fileBytes;
_context.Add(fileIn);
await _context.SaveChangesAsync();
}
}
}
return View();
}
EDIT
And below is return of files to a list and then download.
public JsonResult GetAllFiles()
{
var files = _context.File
.Include(a => a.FileCategory)
.Select(a => new
{
id = a.Id.ToString(),
fileName = a.Filename,
fileData = a.FileData,
fileType = a.FileType,
friendlyName = a.FriendlyName,
fileCategory = a.FileCategory.Name.ToLower()
}).ToList();
return Json(files);
}
public FileStreamResult DownloadFileById(int id)
{
// Fetching file encoded code from database.
var file = _context.File.SingleOrDefault(f => f.Id == id);
var fileData = file.FileData;
var fileName = file.Filename;
// Converting to code to byte array
byte[] bytes = Convert.FromBase64String(fileData);
// Converting byte array to memory stream.
MemoryStream stream = new MemoryStream(bytes);
// Create final file stream result.
FileStreamResult fileStream = new FileStreamResult(stream, "*/*");
// File name with file extension.
fileStream.FileDownloadName = fileName;
return fileStream;
}

how to upload an image using servlet to an absolute path

I want to upload a file to my project folder. My code is as follows:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File savedFile;
String destination;
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
String userName = (String) session.getAttribute("newUser");
destination = getServletConfig().getServletContext().getContextPath() + "\\" + userName + ".jpeg";
savedFile = new File(destination);
//Check if file exists
if(!savedFile.exists())
savedFile.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));
byte[] buffer = new byte[1024];
int len;
//Read from file and write to new file destination
while((len = fileContent.read(buffer)) >= 0) {
bos.write(buffer, 0, len);
}
//Closing the streams
fileContent.close();
bos.close();
}
}
}
When I run the jsp file and browse and select the required image and submit the form, the servlet runs but it throws IOException. The exception is throws by the line where I create a new path using savedFile.createNewFile(). Before I used that code, it threw another FileNotFoundException. I am not sure if the path that I have provided is correct.
Try to use getRealPath() method.
String fileName="/" + userName + ".jpeg";
destination = getServletContext().getRealPath(fileName);
savedFile = new File(destination);

Resources