This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am doing project Online Image Gallery, in which I have to upload images. I am doing it with jsp/servlet and IDE is Eclipse.
My Jsp file is as follows
<form action="ActionPage" >
<input type="file" name="myFile">
<br>
<input type="submit">
</form>
Here Actionpage is servlet. On Clicking submit button i want the selected file to be stored inside the folder called "IMAGE" inside the WebContent on server and path on database table.
If any one know the simple solution please share it.
Thanks in advance.
You can read how this is done here
How to upload files to server using JSP/Servlet?
PS: Storing uploaded files inside the applications directory is BAD BAD BAD idea. Think about what would happen if you have your application running for some time, and you want to do a redeploy becase a file is missing some html tag. The upload's directory will be removed by your container!
Try using a folder outside of the application's directory, or use a database.
This is the easiest solution if You are using jsp to develop your website
First of all for taking input from user make a html or jsp page and include tis code in your jsp/html page
First of all download
commons-fileupload-1.2.2.jar
org.apache.commons.io.jar
and add this jar to your library by right-clicking your project then select build path and then add jar files
`<form role="form" action="Upload.jsp" method="post"enctype="multipart/form-data">
<div class="btn btn-success btn-file">
<i class="fa fa-cloud-upload"></i>
Browse
<input type="file" name="file" />
</div>
<button type="submit" value="submit" name='submit'>submit</button>`
</form>
enctype="multipart/form-data"
it is necessary
Now make one jsp named upload.jsp( you can have the target jsp with which we are going to save our image to server of any name but remember to put that name in in above code
<%# page import="java.io.*,java.util.*, javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.io.output.*" %>
<%
String userName = (String) session.getAttribute("User");
File file ;
int maxFileSize = 5000000 * 1024;
int maxMemSize = 5000000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("C:\\Users\\"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
request.setAttribute("Success", "Successfully Uploaded");
RequestDispatcher rd = request.getRequestDispatcher("/UploadFiles.jsp");
rd.forward(request, response);
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}else{
request.setAttribute("Error", "Error!!");
RequestDispatcher rd =request.getRequestDispatcher("/UploadFiles.jsp");
rd.forward(request, response);
}
%>
please don't get confused just copy this code and once you go through this i am sure you will get to know about code
Now the last thin you have to do is to add something to web.xml if you don't have this file then create this...
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\\Users\\
</param-value>
</context-param>
just add above code to web.xml you can change the address where your images will be uploaded as desired ( change param-value for this)
In case you face any problem let me know
Related
I am using Vuetify in my VueJs project and I need to send data from my form in which I am uploading a file (CSV) and got some number inputs. I need to do that with Axios.
I've tried to do something but always got a 404.
This is my Vuetify code:
<v-form>
<v-container>
<v-row>
<v-file-input
show-size
counter
multiple
label="Nacitaj CSV"
ref="myfile"
v-model="files"
></v-file-input>
</v-row>
<v-row>
<v-col>
<v-text-field
type="number"
label="zadaj cislo"
/>
</v-col>
<v-col>
<v-text-field
type="number"
label="zadaj cislo"
/>
</v-col>
</v-row>
<v-row>
<v-col :cols="2">
<v-btn
block
color="primary"
#submit="submitFiles"
>
Submit
</v-btn>
</v-col>
</v-row>
</v-container>
</v-form>
methods: {
submitFiles() {
if (this.files) {
let formData = new FormData();
// files
for (let file of this.files) {
formData.append("files", file, file.name);
}
// additional data
formData.append("test", "foo bar");
axios.post("/about", formData);
}
I've tried the script which I found on internet but it wasn't working; also the script was only for the file.
I know this is super old but for the next person arriving at this answer, let's take a look at submitFiles function:
submitFiles() {
if (this.files) {
let formData = new FormData();
// files
for (let file of this.files) {
formData.append("files", file, file.name);
}
// additional data
formData.append("test", "foo bar");
axios.post("/about", formData);
}
the first if is checking if files is not empty. files is part of the model. If there are files it creates a new object to hold the Form data (formData).
Then it will loop the files object and append the files to the object holding the form data and after that it will append a field called test with the value foo bar and make a post request to /about in the domain you're serving your page sending the form data object as the body. If you're getting a 404 it should mean that about doesn't exist.
I use an input file to load data from a xml file.
HTML Code:
<button (click)="xmlFile.click()" id="btnLoadXmlFile">
Load data from file
</button>
<input type="file" (change)="handleFileInput($event)" accept="text/xml" class="load-xml-file" id="inputLoadXML" #xmlFile>
<span>{{ chosenFile }}</span>
E2E Code:
it( "Should load data from XML file", () => {
const path = require('path');
const fileToUpload = '../../src/assets/xml/myXmlFile.xml',
absolutePath = path.resolve(__dirname, fileToUpload);
componentPo.getDomElements().btnLoadXML.click();
componentPo.getDomElements().inputLoadXML.sendKeys(absolutePath);
});
It works fine except not being able to close the finder window (Mac User) after selecting the file and loading the data. This also causes that the E2E fails.
Any hint or idea how to fix this and force the Finder window to be closed after selecting the file?
No need to click on that File Upload button to upload a file. sendKeys will do that for you. Please remove componentPo.getDomElements().btnLoadXML.click(); from your existing code.
it( "Should load data from XML file", () => {
const path = require('path');
const fileToUpload = '../../src/assets/xml/myXmlFile.xml',
absolutePath = path.resolve(__dirname, fileToUpload);
componentPo.getDomElements().inputLoadXML.sendKeys(absolutePath);
});
I have got a set 3 HTML Pages
I am using Apache Tomcat 7 server . I have got the following HTML pages (All are HTML pages only)
login.html
sales.html
index.html
The code for the login.html is when clicked on submit is
<input type="email" name="email" id="email" >
<input type="pin" name="email" id="pin" >
<button class="primary login-btn">Submit</button>
Once clicked on Submit button , i am calling a Jersey REST Webservce this way and will response either true OR false based on the values present in our Database
function submitLoginForm() {
var email_input = $.trim($("#email").val());
var pin_input = $.trim($("#pin").val());
var logininfo = {
'email': email_input,
'pin': pin_input
};
var login_information = JSON.stringify(logininfo);
$.ajax({
type: 'POST',
dataType: 'json',
data: login_information,
url: url + '/HEGS/orn/webchecklogin',
success: function(response) {
// if true , redirect to sales.html page
window.location = "index.html"
},
});
}
All this is working fine , my issue is , how can i stop the prevent the user from accessing the page directly
For example if he types the follwing URL
http:localhost:8080/HEGS/dealer/sales.html
You would want to redirect the url to one file, which would then load the correct file based on the criteria you set. I don't know much about Tomcat, but this article seems to explain it well under the "URL Rewriting" section.
I am new to these technologies and hence have limited knowledge on how to upload a file. During my research, I have seen ngUpload and other javascript/directive based solutions. However, I am trying the following and not sure what else I am missing to complete it.
I am trying to upload file after creating a blog using angular-express-blog application. I have the following code
In view.jade
fieldset
h5 Add Media
form(name='theForm', enctype="multipart/form-data")
.clearfix
label Document Name
.input: input(ng-model='form.docName', name='docName', type='text')
.clearfix
label File
.input: input(ng-model='form.file', type="file", name="file")
.actions
button(ng-click="uploadFiles('/page3files')") Upload Files
the controller, I do need to return to the uploadfile page hence, I am passing in /page3files.
$scope.uploadFiles = function( path ) {
//alert("upload files clikced");
$http.post('/api/uploadFile', $scope.form).
success(function(data) {
$scope.form.docName='';
$scope.form.file='';
$location.path(path);
});
};
In the express routes file
exports.uploadFile = function (req, res) {
console.log("doc name: " + req.body.docName);
console.log("file name: " + req.body.file.name);
console.log("file path: " + req.body.file.path);
res.json(true);
};
Unfortunately, I am getting an exception at req.body.file.name saying cannot read property 'name' of undefined.
Any assistance is much appreciated.
Thanks,
Melroy
for the $http.post() to be able to upload files you need to set some configurations.
headers : {'Content-Type': undefined},
transformRequest: angular.identity
You can use the simple/lightweight angular-file-upload directive that takes care of that for you.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim.
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
There are more info on the README page and there is a Demo page
You can send file data with FormData object. For Example:
HTML:
<fieldset>
<legend>Upload Video</legend>
<input type="file" name="photo" id="photo">
<input type="button" ng-click="uploadVideo()" value="Upload">
</fieldset>
JS:
$scope.uploadVideo = function () {
var photo = document.getElementById("photo");
var file = photo.files[0];
var fd = new FormData(); //Create FormData object
fd.append('file', file);
$http.post('/uploadVideo', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
// Do your work
});
};
i am new to SWFUpload , and i am reading the documentation now, and i need an example using SWFUpload with java please, thank you.
Example implementation for SWFUpload, jQuery, JSP, Java and Spring
First the jsp:
<%# page language="java" pageEncoding="UTF-8" %>
<head>
<script type="text/javascript" src="<c:url value="/public/js/swfupload/swfupload.js"/>"></script>
<script type="text/javascript" src="<c:url value="/public/js/jquery-plugins/ jquery.swfupload.js"/>"></script>
<script type="text/javascript">
$(function(){
$('.swfupload-control').swfupload({
// Backend Settings
upload_url: "<c:url value="/upload;jsessionid=${pageContext.session.id}"/>", // Relative to the SWF file (or you can use absolute paths)
// Flash Settings
flash_url : "<c:url value="/public/js/swfupload/swfupload.swf"/>",
//IMPORTANT: you need to set file_post_name otherwise flash sets it as Filedata, which does not conform to bean naming conventions.
file_post_name: "file",
// File Upload Settings
file_size_limit : "102400", // 100MB
file_types : "*.*",
file_types_description : "All Files",
file_upload_limit : "10",
file_queue_limit : "0",
// Button Settings
button_image_url : "<c:url value="/public/js/swfupload/XPButtonUploadText_61x22.png"/>", // Relative to the SWF file
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22
});
// assign our event handlers
$('.swfupload-control')
.bind('fileQueued', function(event, file){
// start the upload once a file is queued
$(this).swfupload('startUpload');
})
.bind('uploadComplete', function(event, file){
alert('Upload completed - '+file.name+'!');
// start the upload (if more queued) once an upload is complete
$(this).swfupload('startUpload');
});
});
</script>
<head>
<body>
<div id="file_upload"></div>
<div class="swfupload-control">
<span id="spanButtonPlaceholder"></span>
</div>
</body>
Controller:
#Controller
public class UploadController {
Logger logger = LoggerFactory.getLogger(this.getClass());
#RequestMapping(value="/upload", method=RequestMethod.POST)
public String addMultiple(
final HttpServletRequest request
, final HttpServletResponse response
, #RequestParam("file") MultipartFile file //NOTE: `#RequestParam("file")` matches `file_post_name: "file"`
){
logger.debug(uploadedFile.getOriginalFilename());
}
}
Also, make sure you've got this in your configs:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
If you are not using spring you might be able to cast the HttpServeletRequest as a MultiPartRequestWrapper use:
File[] files = ((MultiPartRequestWrapper)request).getFiles("Filedata");
This solution doesn't require COS (Com O'Reilly Servlet). Instead it just uses the more common javax.servlet.http.HttpServletRequest
Sources (stackoverflow wouldnt let me post links):
swfupload.org/forum/generaldiscussion/1087
demo.swfupload.org/Documentation/#setFilePostName
blogs.bigfish.tv/adam/2009/06/14/swfupload-jquery-plugin/
webdeveloperplus.com/jquery/multiple-file-upload-with-progress-bar-using-jquery/ (prettier implemenation of jquery uploader)
http://e-blog-java.blogspot.com/2011/03/upload-using-swfupload-component.html
He had also given a sample source code to see it in action.