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

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?

Related

How to fix NullPointerException when uploading picture in database?

I want to upload a picture in database, and this is my jsp:
<body>
<form action="addbooka" method="POST" enctype="multipart/form-data">
Title:<input type="text" value="${title}" name="title"> <br>
Description: <input type="text" value="${description}" name="description"><br>
Price: <input type="text" value="${price}" name="price"><br>
Picture: <input type="file" name="myimg"><br>
<button type="submit">Add</button>
</form>
</body>
And this is method where i insert picture:
public static void insertImage(String myImage) throws Exception {
try {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
File file = new File(myImage);
InputStream in = new FileInputStream(file);
ps.setBlob(1, in);
ps.executeUpdate();
In servlet i just call this method and pass request.getParameter("myimg") as an argument(input tag).
After some research i think i get this error because i did't put boundary in form tag. But i can't wrap my head around what numbers to put, what to do next or is it really error because of boundary or something else?
In your servlet don't forget to put #MultipartConfig annotation.Also , you are passing string to your method instead that should be Part . i.e :
int row=0;
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("myimg");//get image
insertImage(filePart)//pass to method
public static void insertImage(Part filePart) throws Exception {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
if (filePart != null) {
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
ps.setBlob(1, inputStream);
}
row = ps.executeUpdate();
if (row > 0) {
out.println("done")
}
}

Cannot get Blazor file upload to upload file

I have a Blazor app where Im using BlazorInputFile from this website - https://blog.stevensanderson.com/2019/09/13/blazor-inputfile/ however the page only loads it to a Memory Stream, not copy the file to a folder on the server. I need it to copy to a folder on the server.
<div class="form-group">
<label for="taskName">Feature Image</label>
<InputFile OnChange="HandleFileSelected" />
</div>
#code {
IFileListEntry file;
void HandleFileSelected(IFileListEntry[] files)
{
file = files.FirstOrDefault();
}
async Task CountLines()
{
numLines = 0;
using (var reader = new System.IO.StreamReader(file.Data))
{
while (await reader.ReadLineAsync() != null)
{
numLines++;
}
}
}
async Task UploadFile()
{
if (file != null)
{
var path = System.IO.Path.Combine(Server.MapPath("~/Uploads/"));
string pathstring = System.IO.Path.Combine(path.ToString());
string filename1 = Guid.NewGuid() + System.IO.Path.GetExtension(file.Name);
bool isexists = System.IO.Directory.Exists(path);
if (!isexists)
{
System.IO.Directory.CreateDirectory(pathstring);
}
string uploadpath = pathstring + "\\" + filename1;
file.SaveAs(uploadpath);
}
}
In the code above I have created a UploadFile method and taken my usual way of uploading files, but obviously it wont work because IFileListEntry does not have the SaveAs method and Server will not work on Blazor.
How am I best uploading this file to the server please? (UploadFile method will get called on form submit).

File upload in Spring boot to add in sql db

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
}

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" /">"

SharePoint 2010

We are working on an assignment to create a web application using SharePoint 2010 which is totally new to all of us.
My challenge is creating a file upload form. I used SharePoint designer to drag the upload texbox and button controls from the ASP.NET tool box. I don't know what to do next because I need the files to go where I want.
Here is the code that I have for the control I palced on the page:
<form id="form1" runat="server">
<asp:FileUpload runat="server" id="FileUpload1" /><br />
<br />
<asp:Button runat="server" Text="Upload" id="Button1" Width="88px" />
</form>
This routine will upload a single file assuming you've implemented the FileUpload control on your page. the routine gets the file name from the FileUpload control and adds it to a SharePoint list:
protected void UploadButton_Click(object sender, EventArgs e)
//=================================================
// upload the file selected in the upload button to the library
//
//=================================================
{
string docLibName = "/documents/Forms/AllItems.aspx";
if (FileUpload.HasFile)
{
try
{
int orderID = Convert.ToInt32(ViewState["OrderID"].ToString());
string status = ddlDocumentStatus.SelectedValue;
string docType = ddlDocumentType.SelectedValue;
// Read the file contents into a byte stream
string filename = FileUpload.FileName;
byte[] contents = new byte[FileUpload.FileContent.Length];
System.IO.Stream myStream;
int fileLen = FileUpload.PostedFile.ContentLength;
myStream = FileUpload.FileContent;
myStream.Read(contents, 0, fileLen);
// Upload the file to "Documents" Library
using (SPSite oSite = new SPSite(_siteURL))
using (SPWeb oWeb = oSite.OpenWeb())
{
docLibName = _siteURL + docLibName;
SPWeb site = new SPSite(docLibName).OpenWeb();
// Copy the file to the sharepoint library
SPFolder myLibrary = oWeb.Folders["Documents"];
// try checking out the file, if it doesn't exist, create it:
SPFile spfile = null;
try
{
spfile = oWeb.GetFile(_siteURL + "/Documents/" + filename);
if (spfile.Exists)
{
spfile.CheckOut();
myLibrary.Files.Add(filename, myStream, true);
}
else // create a new document
{
spfile = myLibrary.Files.Add(filename, myStream, true);
}
SPListItem document = spfile.Item;
// Copy the metadata to the document
//spfile.Item;
// update the metadata for the document here
document["Columns Name"] = some_string_value;
document["Document Type"] = docType;
myLibrary.Update();
document.Update();
spfile.CheckIn("Document updated on " + DateTime.Today.ToString());
}
catch (Exception ex)
{
string errorMessage = ex.Message;
}
// update the sharepoint list
SPList docLib = oWeb.Lists["Documents"];
AddDocuments(orderID, docLib);
lblDocumentMessage.Text = "Document uploaded!";
}// using - Disposes Site and web
}// try
catch (Exception ex)
{
string errorMessage = ex.Message;
lblDocumentMessage.Text = "Document upload error: " + errorMessage;
}
}
}