在java中读取文件上传的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31099956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
read the contents of a file upload in java
提问by coder
I know how to upload a file:
我知道如何上传文件:
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
File :<input type="file" name="file" size="50" />
<input type="submit" value="Upload File"/>
</form>
</body>
</html>
This is the class for reading the file:
这是读取文件的类:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now how do you link both these together. The user uploads the file onto the server and the server processes it. i.e., it accepts the file and prints it contents. Can I use struts framework for this? I want to upload excel sheet and print the contents to the jsp page. I have the code for reading the excel sheet in java using apache poi. But the path to read the excel file is hard coded. how do you take it from the uploaded file?
现在你如何将这两者联系在一起。用户将文件上传到服务器上,服务器对其进行处理。即,它接受文件并打印其内容。我可以为此使用struts框架吗?我想上传excel表并将内容打印到jsp页面。我有使用 apache poi 在 java 中读取 excel 表的代码。但是读取excel文件的路径是硬编码的。你如何从上传的文件中获取它?
This is the file for reading excel sheet:
这是读取excel表的文件:
public class ReadExcelDemo
{
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
输出:
ID NAME LASTNAME
1.0 Amit Shukla
2.0 Lokesh Gupta
3.0 John Adwards
4.0 Brian Schultz
ID NAME LASTNAME 1.0 Amit Shukla 2.0 Lokesh Gupta
3.0 John Adwards 4.0 Brian Schultz
But how do you stitch the uploaded and the servlet file together. How do you read the uploaded file?
但是如何将上传的文件和servlet 文件拼接在一起。你如何阅读上传的文件?
采纳答案by coder
I got it. The index file(html) is for uploading the file (as above in my qquestion) The java class for it is:
我知道了。索引文件(html)用于上传文件(如上面我的问题)它的java类是:
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
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:\temp"));
// 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 fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
String fileName = "";
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
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 ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
out.println("Uploaded in location: "+filePath);
}
}
out.println("</body>");
out.println("</html>");
ReadExcelDemo rd = new ReadExcelDemo();
System.out.println("file name: "+fileName.substring(fileName.lastIndexOf("\")));
String s = fileName.substring(fileName.lastIndexOf("\"));
System.out.println(filePath);
System.out.println(s);
String fileP = filePath.concat(s+"\");
System.out.println(fileP);
rd.read(fileP);
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
This is the class for reading the excel sheet using apache poi jars:
这是使用 apache poi jars 读取 excel 表的类:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelDemo {
public static void read(String filePath) {
// public static void main(String[] args){
try {
FileInputStream file = new FileInputStream(new File(filePath));
// FileInputStream file = new FileInputStream(new File("C:\work\demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
/* int row=0;
int k=1;
Row myRow = sheet.createRow ((short)row);
myRow.createCell(k).setCellValue ("new data");
myRow = sheet.createRow ((short)row++); */
// Cell cell1 = sheet. // Access the second cell in second row to update the value
// cell1.setCellValue("OverRide Last Name");
Cell cell1 = null; // declare a Cell object
cell1 = sheet.getRow(2).getCell(2); // Access the second cell in second row to update the value
cell1.setCellValue("OverRide Last Name");
file.close();
/* FileOutputStream out = new FileOutputStream(new File("write_demo1.xlsx"));
workbook.write(out);
out.close(); */
}
catch (Exception e) {
e.printStackTrace();
}
}
}
回答by Chris Morgan
Like many operations in Java, reading a file upload is unneccessarily complex, and difficult to work out from the javadocs. You are already planning to use Apache libraries to read your uploaded file, so I recommend using apache.commons.fileupload to upload your file as well.
与 Java 中的许多操作一样,读取文件上传不必要地复杂,并且难以从 javadoc 中解决。您已经计划使用 Apache 库来读取您上传的文件,因此我建议您也使用 apache.commons.fileupload 来上传您的文件。
This code fragment uploads a CSV file into a string:
此代码片段将 CSV 文件上传到字符串中:
...
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
...
if (ServletFileUpload.isMultipartContent(request)) {
int i=0;
DiskFileItemFactory factory = new DiskFileItemFactory();
// files smaller than 5MB will be held in memory
factory.setSizeThreshold(5000000);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(10000000); // max size of attachment 10MB
List list = upload.parseRequest(request);
Iterator iter = list.iterator();
String csv = null;
while (iter.hasNext()) {
FileItem param = (FileItem)iter.next();
if (!param.isFormField()) {
csv = param.getString();
break;
}
}
if (csv==null) {
throw new Exception("CSV buffer not uploaded");
}
}
回答by Lalit Chattar
You can achieve it by breaking whole process in two steps
您可以通过将整个过程分为两步来实现
1) Upload file
1) 上传文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
}
// displays done.jsp page after upload finished
getServletContext().getRequestDispatcher("/done.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
2) After upload pass file location to the method which read file data using apche poi. Use File uploadedFile = new File(filePath);
object to get file location.
2)上传后通过文件位置到使用apche poi读取文件数据的方法。使用 File uploadedFile = new File(filePath);
对象获取文件位置。