File upload in Spring boot to add in sql db - sql

I am working on the code but stuck. It should be able to read image file from web browser and convert into blob for sql db. I am using spring boot, hibernate, sql. no js or xml. The controller and the html codes are listed below.
#Controller
#RequestMapping("imagefile")
public class ImagefileController {#RequestMapping(value = "menu", method = RequestMethod.POST)
public String imageupload(Model model, #RequestParam("id") int id, #RequestParam("uploadFile") MultipartFile uploadFile,
RedirectAttributes redirectAttributes) {
//add photo upload coding here.
String filename=uploadFile.getOriginalFilename();
String uploadFilepath=Paths.get("." + File.separator, filename).toString();;
//need to get the file into the input stream.
//byte[] bytes = uploadFile.getBytes();
//String filename1 = uploadFile.toString();
//File f = new File(filename1);
//f.getAbsolutePath();
//FileInputStream fis = new FileInputStream(f.getAbsoluteFile());
//f.getAbsolutePath();
Byte [] imagefile;
//InputStream is = new FileInputStream(new File(filename1));
//File filename = new FileInputStream(filename1.getBytes());
//String uploadFilename = uploadFile.getOriginalFilename();
//createSessionFactory().openSession();
//Session session = sessionFactory.getSessionFactory().openSession(); //getSessionFactory().getCurrentSession();
//File uploadfile = new File(uploadfile);
// Blob fileblob = Hibernate.getLobCreator(session).createBlob(filename.getBytes()); //new FileInputStream(uploadfile), file1.length()
Menu menu = menuDao.findOne(id);
model.addAttribute("title", "Add images to the menu: " + menu.getName());
System.out.println("Original Filename is:" + uploadFile.getOriginalFilename());
System.out.println("File Class is:" + uploadFile.getClass());
System.out.println("Is the File Empty?:" + uploadFile.isEmpty());
System.out.println("File size:" + uploadFile.getSize());
System.out.println("File contentType:" + uploadFile.getContentType());
//session.close();
return "Imagefile/index";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/" xmlns:form="http://www.w3.org/1999/xhtml">
<head th:replace="fragments :: head"></head>
<body class="container">
<nav th:replace="fragments :: navigation"></nav>
<h1 th:text="${title}"></h1>
<form method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" id="file" title=" " accept="image/*"/>
<p></p>
<input type="submit" value="add photo" />
</form>
</body>
</html>
-----dao------
#Repository
#Transactional
public interface MenuDao extends CrudRepository<Menu, Integer>{
}
-------entity for sql----
#Entity
public class Imagefile {
#Id
#GeneratedValue
private int id;
private String filename;
#Lob
private Blob imagecontent;
#ManyToOne
private Menu menu;
//constructor
public Imagefile(int id, String filename, Blob imagecontent) {
this.id = id;
this.filename = filename;
this.imagecontent = imagecontent;
}
public Imagefile() {}
//Getters and Setters - Accessors.
public int getId() {
return id;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Blob getImagecontent() {
return imagecontent;
}
public void setImagecontent(Blob imagecontent) {
this.imagecontent = imagecontent;
}
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
}
Here is the output for the test.
Original Filename is:40 Brookside.jpg
File Class is:class org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile
Is the File Empty?:false
File size:473735
File contentType:image/jpeg

Here how I'll proceed to store the file in FileSystem and path in DB.
public String imageupload(#RequestPart("uploadFile") MultipartFile uploadFile,...) {
String FILES_FOLDER = "C:/MyFilesDirectory/";
String PHOTOS_FOLDER= "PHOTOS/";
String photoName = uploadFile !=null ? uploadFile.getOriginalFileName(): null;
String DIRECTORY = FILES_FOLDER+PHOTOS_FOLDER+photoName;
//Now we transfer the file to DIRECTORY
File file = new File(DIRECTORY);
//check if 'file' does not exist then create it
// finally :
uploadFile.transferTo(file);
//Then save 'DIRECTORY' in your db
menuDao.save(DIRECTORY); // I don't know what is inside your menuDao
}
Note that I am using #RequestPart instead of #RequestParam.
EDIT: LOADING FILE
Example of code for displaying your image. Let's suppose you have this in your view
<img src="get-image" />
Then in your handler method you will have :
#RequestMapping("get-image" )
#ResponseBody
public byte[] getImage(){
//retrieve your image from DB
//transform it to byte[]
// then return it
}

Related

Blazor Server: Creating email attachments from files uploaded via InputFile

I am trying to send emails with attachments attached to the email. I have a InputFile with a progress bar that I am able to upload files. I have attempted to use the memory stream to make attachments to the MailMessage class. The issue is that when the email is received, I am able to see the attachments but I can't read or view the contents of the attachments. I've posted my code below so you can replicate the issue that I am having (Make sure to install the Meziantou.Framework.ByteSize nuget package)
#using System.Net.Mail
#using System.Globalization
#using Meziantou.Framework
<InputFile OnChange="e => LoadFiles(e)" multiple></InputFile>
#foreach (var file in uploadedFiles)
{
<div>
#file.FileName
<progress value="#file.UploadedBytes" max="#file.Size"></progress>
#file.UploadedPercentage.ToString("F1")%
(#FormatBytes(file.UploadedBytes) / #FormatBytes(file.Size))
</div>
}
<button type="button" #onclick="#HandleNotifSubmit" class="btn btn-primary submit">Send Email</button>
#code {
private MemoryStream fileContents { get; set; }
List<FileUploadProgress> uploadedFiles = new();
MailMessage message = new MailMessage();
StreamWriter writer { get; set; }
private async ValueTask LoadFiles(InputFileChangeEventArgs e)
{
var files = e.GetMultipleFiles(maximumFileCount: 100);
var startIndex = uploadedFiles.Count;
// Add all files to the UI
foreach (var file in files)
{
var progress = new FileUploadProgress(file.Name, file.Size);
uploadedFiles.Add(progress);
}
// We don't want to refresh the UI too frequently,
// So, we use a timer to update the UI every few hundred milliseconds
await using var timer = new Timer(_ => InvokeAsync(() => StateHasChanged()));
timer.Change(TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(500));
// Upload files
byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(4096);
try
{
foreach (var file in files)
{
using var stream = file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
while (await stream.ReadAsync(buffer) is int read && read > 0)
{
uploadedFiles[startIndex].UploadedBytes += read;
var readData = buffer.AsMemory().Slice(0, read);
}
fileContents = new MemoryStream(buffer);
writer = new StreamWriter(fileContents);
fileContents.Position = 0;
message.Attachments.Add(new Attachment(fileContents, file.Name));
startIndex++;
}
}
finally
{
System.Buffers.ArrayPool<byte>.Shared.Return(buffer);
StateHasChanged();
}
}
string FormatBytes(long value)
=> ByteSize.FromBytes(value).ToString("fi2", CultureInfo.CurrentCulture);
record FileUploadProgress(string FileName, long Size)
{
public long UploadedBytes { get; set; }
public double UploadedPercentage => (double)UploadedBytes / (double)Size * 100d;
}
private async void HandleNotifSubmit()
{
try
{
var sClient = new SmtpClient("FAKECOMPANYCLIENT");
sClient.Port = 25;
sClient.UseDefaultCredentials = false;
message.Subject = "Hello World";
message.From = new MailAddress("test#gmail.com");
message.IsBodyHtml = true;
message.To.Add(new MailAddress("Fake#gmail.com"));
message.Body = "Please view attachments below.";
sClient.Send(message);
message.Dispose();
}
catch
{
Console.WriteLine("error");
}
}
}
I have also tried to use a stream writer with no success. I have also tried various ways to do a file.CopyToAsync(memoryStreamname). I am not sure what else I am missing or doing wrong here.
Thank you in advance.

"multipart config was not present on Servlet" when trying to upload a file with JAX-RS class

I have the following JAX-RS class to upload a file from a browser (implemented in Wildfly 14). Problem is I get the error multipart config was not present on Servlet. Since I annotated the class with #Consumes({ MediaType.MULTIPART_FORM_DATA }) I'm not sure what is missing. How to fix this problem?
#Produces({ MediaType.APPLICATION_JSON })
#Consumes({ MediaType.MULTIPART_FORM_DATA })
public class FileUploadService {
#Context
private HttpServletRequest request;
#POST
#Path("/upload")
public Response processUpload() throws IOException, ServletException {
String path = "/mypath";
for (Part part : request.getParts()) {
String fileName = getFileName(part);
String fullPath = path + File.separator + fileName;
// delete file if exists
java.nio.file.Path path2 = FileSystems.getDefault().getPath(fullPath);
Files.deleteIfExists(path2);
// get file input stream
InputStream fileContent = part.getInputStream();
byte[] buffer = new byte[fileContent.available()];
fileContent.read(buffer);
File targetFile = new File(fullPath);
// write output file
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
}
return Response.ok("OK").build();
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename"))
return content.substring(content.indexOf("=") + 2, content.length() - 1);
}
return "";
}
}

How can I use iText to convert HTML with images and hyperlinks to PDF?

I'm trying to convert HTML to PDF using iTextSharp in an ASP.NET web application that uses both MVC, and web forms. The <img> and <a> elements have absolute and relative URLs, and some of the <img> elements are base64. Typical answers here at SO and Google search results use generic HTML to PDF code with XMLWorkerHelper that looks something like this:
using (var stringReader = new StringReader(xHtml))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(
writer, document, stringReader
);
}
}
So with sample HTML like this:
<div>
<h3>HTML Works, but Broken in Converted PDF</h3>
<div>Relative local <img>: <img src='./../content/images/kuujinbo_320-30.gif' /></div>
<div>
Base64 <img>:
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' />
</div>
<div><a href='/somePage.html'>Relative local hyperlink, broken in PDF</a></div>
<div>
The resulting PDF: (1) is missing all images, and (2) all hyperlink(s) with relative URLs are broken and use a file URI scheme (file///XXX...) instead of pointing to the correct web site.
Some answers here at SO and others from Google search recommend replacing relative URLs with absolute URLs, which is perfectly acceptable for one-off cases. However, globally replacing all <img src> and <a href> attributes with a hard-coded string is unacceptable for this question, so please do not post an answer like that, because it will accordingly be downvoted.
Am looking for a solution that works for many different web applications residing in test, development, and production environments.
Out of the box XMLWorker only understands absolute URIs, so the described issues are expected behavior. The parser can't automagically deduce URI schemes or paths without some additional information.
Implementing an ILinkProvider fixes the broken hyperlink problem, and implementing an IImageProvider fixes the broken image problem. Since both implementations must perform URI resolution, that's the first step. The following helper class does that, and also tries to make web (ASP.NET) context calls (examples follow) as simple as possible:
// resolve URIs for LinkProvider & ImageProvider
public class UriHelper
{
/* IsLocal; when running in web context:
* [1] give LinkProvider http[s] scheme; see CreateBase(string baseUri)
* [2] give ImageProvider relative path starting with '/' - see:
* Join(string relativeUri)
*/
public bool IsLocal { get; set; }
public HttpContext HttpContext { get; private set; }
public Uri BaseUri { get; private set; }
public UriHelper(string baseUri) : this(baseUri, true) {}
public UriHelper(string baseUri, bool isLocal)
{
IsLocal = isLocal;
HttpContext = HttpContext.Current;
BaseUri = CreateBase(baseUri);
}
/* get URI for IImageProvider to instantiate iTextSharp.text.Image for
* each <img> element in the HTML.
*/
public string Combine(string relativeUri)
{
/* when running in a web context, the HTML is coming from a MVC view
* or web form, so convert the incoming URI to a **local** path
*/
if (HttpContext != null && !BaseUri.IsAbsoluteUri && IsLocal)
{
return HttpContext.Server.MapPath(
// Combine() checks directory traversal exploits
VirtualPathUtility.Combine(BaseUri.ToString(), relativeUri)
);
}
return BaseUri.Scheme == Uri.UriSchemeFile
? Path.Combine(BaseUri.LocalPath, relativeUri)
// for this example we're assuming URI.Scheme is http[s]
: new Uri(BaseUri, relativeUri).AbsoluteUri;
}
private Uri CreateBase(string baseUri)
{
if (HttpContext != null)
{ // running on a web server; need to update original value
var req = HttpContext.Request;
baseUri = IsLocal
// IImageProvider; absolute virtual path (starts with '/')
// used to convert to local file system path. see:
// Combine(string relativeUri)
? req.ApplicationPath
// ILinkProvider; absolute http[s] URI scheme
: req.Url.GetLeftPart(UriPartial.Authority)
+ HttpContext.Request.ApplicationPath;
}
Uri uri;
if (Uri.TryCreate(baseUri, UriKind.RelativeOrAbsolute, out uri)) return uri;
throw new InvalidOperationException("cannot create a valid BaseUri");
}
}
Implementing ILinkProvider is pretty simple now that UriHelper gives the base URI. We just need the correct URI scheme (file or http[s]):
// make hyperlinks with relative URLs absolute
public class LinkProvider : ILinkProvider
{
// rfc1738 - file URI scheme section 3.10
public const char SEPARATOR = '/';
public string BaseUrl { get; private set; }
public LinkProvider(UriHelper uriHelper)
{
var uri = uriHelper.BaseUri;
/* simplified implementation that only takes into account:
* Uri.UriSchemeFile || Uri.UriSchemeHttp || Uri.UriSchemeHttps
*/
BaseUrl = uri.Scheme == Uri.UriSchemeFile
// need trailing separator or file paths break
? uri.AbsoluteUri.TrimEnd(SEPARATOR) + SEPARATOR
// assumes Uri.UriSchemeHttp || Uri.UriSchemeHttps
: BaseUrl = uri.AbsoluteUri;
}
public string GetLinkRoot()
{
return BaseUrl;
}
}
IImageProvider only requires implementing a single method, Retrieve(string src), but Store(string src, Image img) is easy - note inline comments there and for GetImageRootPath():
// handle <img> elements in HTML
public class ImageProvider : IImageProvider
{
private UriHelper _uriHelper;
// see Store(string src, Image img)
private Dictionary<string, Image> _imageCache =
new Dictionary<string, Image>();
public virtual float ScalePercent { get; set; }
public virtual Regex Base64 { get; set; }
public ImageProvider(UriHelper uriHelper) : this(uriHelper, 67f) { }
// hard-coded based on general past experience ^^^
// but call the overload to supply your own
public ImageProvider(UriHelper uriHelper, float scalePercent)
{
_uriHelper = uriHelper;
ScalePercent = scalePercent;
Base64 = new Regex( // rfc2045, section 6.8 (alphabet/padding)
#"^data:image/[^;]+;base64,(?<data>[a-z0-9+/]+={0,2})$",
RegexOptions.Compiled | RegexOptions.IgnoreCase
);
}
public virtual Image ScaleImage(Image img)
{
img.ScalePercent(ScalePercent);
return img;
}
public virtual Image Retrieve(string src)
{
if (_imageCache.ContainsKey(src)) return _imageCache[src];
try
{
if (Regex.IsMatch(src, "^https?://", RegexOptions.IgnoreCase))
{
return ScaleImage(Image.GetInstance(src));
}
Match match;
if ((match = Base64.Match(src)).Length > 0)
{
return ScaleImage(Image.GetInstance(
Convert.FromBase64String(match.Groups["data"].Value)
));
}
var imgPath = _uriHelper.Combine(src);
return ScaleImage(Image.GetInstance(imgPath));
}
// not implemented to keep the SO answer (relatively) short
catch (BadElementException ex) { return null; }
catch (IOException ex) { return null; }
catch (Exception ex) { return null; }
}
/*
* always called after Retrieve(string src):
* [1] cache any duplicate <img> in the HTML source so the image bytes
* are only written to the PDF **once**, which reduces the
* resulting file size.
* [2] the cache can also **potentially** save network IO if you're
* running the parser in a loop, since Image.GetInstance() creates
* a WebRequest when an image resides on a remote server. couldn't
* find a CachePolicy in the source code
*/
public virtual void Store(string src, Image img)
{
if (!_imageCache.ContainsKey(src)) _imageCache.Add(src, img);
}
/* XMLWorker documentation for ImageProvider recommends implementing
* GetImageRootPath():
*
* http://demo.itextsupport.com/xmlworker/itextdoc/flatsite.html#itextdoc-menu-10
*
* but a quick run through the debugger never hits the breakpoint, so
* not sure if I'm missing something, or something has changed internally
* with XMLWorker....
*/
public virtual string GetImageRootPath() { return null; }
public virtual void Reset() { }
}
Based on the XML Worker documentation it's pretty straightforward to hook the implementations of ILinkProvider and IImageProvider above into a simple parser class:
/* a simple parser that uses XMLWorker and XMLParser to handle converting
* (most) images and hyperlinks internally
*/
public class SimpleParser
{
public virtual ILinkProvider LinkProvider { get; set; }
public virtual IImageProvider ImageProvider { get; set; }
public virtual HtmlPipelineContext HtmlPipelineContext { get; set; }
public virtual ITagProcessorFactory TagProcessorFactory { get; set; }
public virtual ICSSResolver CssResolver { get; set; }
/* overloads simplfied to keep SO answer (relatively) short. if needed
* set LinkProvider/ImageProvider after instantiating SimpleParser()
* to override the defaults (e.g. ImageProvider.ScalePercent)
*/
public SimpleParser() : this(null) { }
public SimpleParser(string baseUri)
{
LinkProvider = new LinkProvider(new UriHelper(baseUri, false));
ImageProvider = new ImageProvider(new UriHelper(baseUri, true));
HtmlPipelineContext = new HtmlPipelineContext(null);
// another story altogether, and not implemented for simplicity
TagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
CssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
}
/*
* when sending XHR via any of the popular JavaScript frameworks,
* <img> tags are **NOT** always closed, which results in the
* infamous iTextSharp.tool.xml.exceptions.RuntimeWorkerException:
* 'Invalid nested tag a found, expected closing tag img.' a simple
* workaround.
*/
public virtual string SimpleAjaxImgFix(string xHtml)
{
return Regex.Replace(
xHtml,
"(?<image><img[^>]+)(?<=[^/])>",
new MatchEvaluator(match => match.Groups["image"].Value + " />"),
RegexOptions.IgnoreCase | RegexOptions.Multiline
);
}
public virtual void Parse(Stream stream, string xHtml)
{
xHtml = SimpleAjaxImgFix(xHtml);
using (var stringReader = new StringReader(xHtml))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
HtmlPipelineContext
.SetTagFactory(Tags.GetHtmlTagProcessorFactory())
.SetLinkProvider(LinkProvider)
.SetImageProvider(ImageProvider)
;
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(HtmlPipelineContext, pdfWriterPipeline);
var cssResolverPipeline = new CssResolverPipeline(CssResolver, htmlPipeline);
XMLWorker worker = new XMLWorker(cssResolverPipeline, true);
XMLParser parser = new XMLParser(worker);
parser.Parse(stringReader);
}
}
}
}
As commented inline, SimpleAjaxImgFix(string xHtml) specifically handles XHR that may send unclosed <img> tags, which is valid HTML, but invalid XML that will break XMLWorker . A simple explanation & implementation of how to receive a PDF or other binary data with XHR and iTextSharp can be found here.
A Regex was used in SimpleAjaxImgFix(string xHtml) so that anyone using (copy/paste?) the code doesn't need to add another nuget package, but a HTML parser like HtmlAgilityPack should be used, since it's turns this:
<div><img src='a.gif'><br><hr></div>
into this:
<div><img src='a.gif' /><br /><hr /></div>
with only a few lines of code:
var hDocument = new HtmlDocument()
{
OptionWriteEmptyNodes = true,
OptionAutoCloseOnEnd = true
};
hDocument.LoadHtml("<div><img src='a.gif'><br><hr></div>");
var closedTags = hDocument.DocumentNode.WriteTo();
Also of note - use SimpleParser.Parse() above as a general blueprint to additionally implement a custom ICSSResolver or ITagProcessorFactory, which is explained in the documentation.
Now the issues described in the question should be taken care of. Called from a MVC Action Method:
[HttpPost] // some browsers have URL length limits
[ValidateInput(false)] // or throws HttpRequestValidationException
public ActionResult Index(string xHtml)
{
Response.ContentType = "application/pdf";
Response.AppendHeader(
"Content-Disposition", "attachment; filename=test.pdf"
);
var simpleParser = new SimpleParser();
simpleParser.Parse(Response.OutputStream, xHtml);
return new EmptyResult();
}
or from a Web Form that gets HTML from a server control:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
using (var stringWriter = new StringWriter())
{
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
ConvertControlToPdf.RenderControl(htmlWriter);
}
var simpleParser = new SimpleParser();
simpleParser.Parse(Response.OutputStream, stringWriter.ToString());
}
Response.End();
or a simple HTML file with hyperlinks and images on the file system:
<h1>HTML Page 00 on Local File System</h1>
<div>
<div>
Relative <img>: <img src='Images/alt-gravatar.png' />
</div>
<div>
Hyperlink to file system HTML page:
<a href='file-system-html-01.html'>Page 01</a>
</div>
</div>
or HTML from a remote web site:
<div>
<div>
<img width="200" alt="Wikipedia Logo"
src="portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png">
</div>
<div lang="en">
English
</div>
<div lang="en">
iText
</div>
</div>
Above two HTML snippets run from a console app:
var filePaths = Path.Combine(basePath, "file-system-html-00.html");
var htmlFile = File.ReadAllText(filePaths);
var remoteUrl = Path.Combine(basePath, "wikipedia.html");
var htmlRemote = File.ReadAllText(remoteUrl);
var outputFile = Path.Combine(basePath, "filePaths.pdf");
var outputRemote = Path.Combine(basePath, "remoteUrl.pdf");
using (var stream = new FileStream(outputFile, FileMode.Create))
{
var simpleParser = new SimpleParser(basePath);
simpleParser.Parse(stream, htmlFile);
}
using (var stream = new FileStream(outputRemote, FileMode.Create))
{
var simpleParser = new SimpleParser("https://wikipedia.org");
simpleParser.Parse(stream, htmlRemote);
}
Quite a long answer, but taking a look at questions here at SO tagged html, pdf, and itextsharp, as of this writing (2016-02-23) there are 776 results against 4,063 total tagged itextsharp - that's 19%.
Very helpful post,
I was problem to render images in my report html to pdf. with your post I could do it.
I'm working with asp.mvc 5.
I only have to change this method of the ImageProviderClass
public virtual string GetImageRootPath() { return null; }
to
public virtual string GetImageRootPath() { HostingEnvironment.MapPath("~/Content/Images/") }
thanks!

How to upload file of p:fileUpload using command button instead of upload button

Iam using JSF2.1 along with primefaces for uploading file.In my application i have to add the file dynamically on creating a record.But when i use
i cant write the code for uploading my file during save.I want the file to be uploaded on click of save only and not during upload.
Can anyone help me how to implement this
public String handleFileUpload(FileUploadEvent event) throws IOException {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
UploadedFile file = event.getFile();
String prefix = FilenameUtils.getBaseName(file.getFileName());
String suffix = FilenameUtils.getExtension(file.getFileName());
String path = "C:/apache-tomcat-7.0.47/webapps/ROOT/WEB-INF/images";
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File fileToDirectory = File.createTempFile(prefix + "-", "." + suffix, new File(path));
InputStream inputStream = event.getFile().getInputstream();
String fileName = event.getFile().getFileName();
OutputStream outputStream = new FileOutputStream(fileToDirectory);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
return path+fileName;
}
I need to have this code on save but i cant get event during save
That isn't possible with auto mode. Use the basic mode instead. Then you can bind the input value to an UploadedFile property directly. This only requires disabling Ajax.
E.g.
<h:form enctype="multipart/form-data">
...
<p:fileUpload mode="simple" value="#{bean.file}" />
...
<p:commandButton value="Save" action="#{bean.save}" ajax="false" />
</h:form>
with
private UploadedFile file; // +getter+setter
public void save() {
try (InputStream input = file.getInputStream()) {
// ...
}
}
The alternative is to migrate to standard JSF <h:inputFile> component which was introduced in JSF 2.2. Then you can continue using Ajax.
E.g.
<h:form enctype="multipart/form-data">
...
<h:inputFile value="#{bean.file}" />
...
<p:commandButton value="Save" action="#{bean.save}" />
</h:form>
with
private Part file; // +getter+setter
public void save() {
try (InputStream input = file.getInputStream()) {
// ...
}
}
See also:
How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

file upload using spring 3

i'm uploading an image file from this page and i'm getting nullpointer exception for multipartfile creation , i'm unable to understand where i did mistake? and i'm newbie for java
fileupload.jsp
<form modelAttribute="uploadFile" name="frm" method="post"
enctype="multipart/form-data" onSubmit="return Validate();">
<form:label for="fileData" path="fileData">File</form:label>
<input path="fileData" id="image" type="file" />
<input type="submit" value="Upload" />
</form>
UploadFile.java
its a bean page with commonsmultiparfile as class member
public class UploadFile {
private String filename;
private CommonsMultipartFile fileData;
/**
* #return the filename
*/
public String getFilename() {
return filename;
}
/**
* #param filename the filename to set
*/
public void setFilename(String filename) {
this.filename = filename;
}
/**
* #return the fileData
*/
public CommonsMultipartFile getFileData() {
return fileData;
}
/**
* #param fileData the fileData to set
*/
public void setFileData(CommonsMultipartFile fileData) {
this.fileData = fileData;
}
}
FileUploadController
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public String fileupload(
serviceOrder,HttpSession session,
ModelMap model, HttpServletRequest request,UploadFile uploadFile,
HttpServletResponse response, Object command, BindingResult result) throws Exception {
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
logger.info("Error: " + error.getCode() + " - "
+ error.getDefaultMessage());
}
return "//fileUpload";
}
try{
MultipartFile multipartFile = uploadFile.getFileData();
InputStream inputStream = null;
OutputStream outputStream = null;
logger.info("---------------"+uploadFile);
logger.info("---------------------------"+multipartFile);
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
// File realUpload = new File("C:/");
outputStream = new FileOutputStream("D:\\Images\\"
+ multipartFile.getOriginalFilename());
logger.info("Original File Name"+multipartFile.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
logger.info("writing data into file.....");
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("uploadFile", "D:\\Images\\"
+ multipartFile.getOriginalFilename());
}
} catch(Exception e) {
e.printStackTrace();
}
i'm uploading an image file from this page and i'm getting nullpointer exception for multipartfile creation , i'm unable to understand where i did mistake? and i'm newbie for java
Change your controller class method to this and give it a try
public String fileupload(HttpSession session,#ModelAttribute UploadFile uploadFile,BindingResult result){
}
I removed the HttpRequest and Response variables as they are not being used and moved the BindingResult object to be next to the ModelAttribute.
Also try to include null checks in the code before accessing the elements.
Did you define the multipartresolver bean
eg you can declare the bean in
"<"bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /">"