文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全激陆郑路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持EXCEL批量导入数据。
java中文件上传到服务器的指定路径的代码:悉孙
在前台界面中输入:
<form method="post" enctype="multipart/form-data" action="../manage/excelImport.do">
请选文件:<input type="file" name="excelFile">
<input type="submit" value="导入" onclick="return impExcel()"/>
</form>
action中获取前台传来数据并保存
/**
* excel 导入文件
* @return
* @throws IOException
*/
@RequestMapping("/usermanager/excelImport.do")
public String excelImport(
String filePath,
MultipartFile excelFile,HttpServletRequest request) throws IOException{
log.info("<<<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" )
if (excelFile != null){
String filename=excelFile.getOriginalFilename()
String a=request.getRealPath("u/cms/www/201509")
SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename)//保存到服务器的路明颂径
}
log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" )
return ""
}
/**
* 将MultipartFile转化为file并保存到服务器上的某地
*/
public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
{
FileOutputStream fs=new FileOutputStream( path + "/"+ savefile)
System.out.println("------------"+path + "/"+ savefile)
byte[] buffer =new byte[1024*1024]
int bytesum = 0
int byteread = 0
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread
fs.write(buffer,0,byteread)
fs.flush()
}
fs.close()
stream.close()
}
servlet类package org.whatisjava.servlet
import java.io.File
import java.io.IOException
import java.util.List
import javax.servlet.ServletContext
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.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
public class UploadServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 用于设此灶正定诸如缓存之类的参数,和性能相辩锋关
// 此处用默认设定
DiskFileItemFactory dfif = new DiskFileItemFactory()
// 解析表单中的数据
ServletFileUpload upload = new ServletFileUpload(dfif)
upload.setSizeMax(10 * 1024 * 1024)// 允许上传的最大值
List list = upload.parseRequest(request)// 开始解析request对象中的表单数据
// list中是FileItem对象
// 一个FileItem用于封装一个上传的文件数据
if (list.size() >= 1) {
FileItem item = (FileItem) list.get(0)
// 获得上文件的森悔路径名
String name = item.getName()
name = name.substring(name.lastIndexOf("\\") + 1)
// 把上传的文件数据写入本地文(服务器端)件文件夹的名字为upload
String path = "upload"
// Sun的标准,服务器实现的API
ServletContext ctx = this.getServletContext()
path = ctx.getRealPath(path)
File file = new File(path)
if(!file.exists()){
System.out.println("创建文件夹")
file.mkdir()
}
System.out.println(path)
System.out.println(name)
//将文件放到指定的地方
item.write(new File(path, name))
response.sendRedirect("upload_form.jsp")
}
} catch (Exception e) {
throw new ServletException("file upload error!", e)
}
}
}
页面<form action="upload" method="post" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
上传
</td>
<td valign="middle" align="left">
<input type="file" class="inputgri" name="file1" />
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="提交 »" />
</p>
</form>
web.xml
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>
org.whatisjava.servlet.UploadServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
jar包
commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar
commons-fileupload-1.2.1-javadoc.jar
commons-fileupload-1.2.1-sources.jar
1.文件上传package com.whw.action
import java.io.File
import javax.servlet.ServletContext
import org.apache.commons.io.FileUtils
import org.apache.struts2.util.ServletContextAware
import com.opensymphony.xwork2.ActionSupport
public class UploadAction extends ActionSupport implements ServletContextAware {
private static final long serialVersionUID = 1L
private File upload// 实际上传文件
private String uploadContentType// 文件的内容类型
private String uploadFileName// 文件 名称
private String fileCaption/备隐昌/ 上传文携铅件时的备注
private ServletContext context
public String execute() throws Exception {
try {
String targetDirectory = context.getRealPath("/upload")
String targetFileName = fileCaption+uploadFileName
File target = new File(targetDirectory, targetFileName)
FileUtils.copyFile(upload, target)
setUploadFileName(target.getPath())//保存文件的存仿扒放路径
} catch (Exception e) {
addActionError(e.getMessage())
return INPUT
}
return SUCCESS
}
public String getFileCaption() {
return fileCaption
}
public void setFileCaption(String fileCaption) {
this.fileCaption = fileCaption
}
public File getUpload() {
return upload
}
public void setUpload(File upload) {
this.upload = upload
}
public String getUploadContentType() {
return uploadContentType
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType
}
public String getUploadFileName() {
return uploadFileName
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName
}
public void setServletContext(ServletContext context) {
this.context = context
}
}
2.读取文件夹下的文件
package sample
import java.io.*
public class CopyFileStream{// copy one file to another file
public static void main(String args[]) {
FileInputStream fromFile=null
FileOutputStream toFile=null
try{
//生成两个已有byte文件的 流对象。
fromFile=new FileInputStream(args[0]) // get file name from console
toFile=new FileOutputStream(args[1]) // get file name from console
} catch (FileNotFoundException e){
System.err.println("File could not be found")
return//缺文件名输入,抛异常,返回。
} catch (IOException e){
System.err.println("File could not be copied ")
return
} catch (ArrayIndexOutOfBoundsException e){
System.err.println("Usage: CopyByteFile from-file to-file")
return
}
try {
fromFile.close() // close InputStream
toFile.close() // close OutputStream
}catch (IOException e){
System.err.println("Error closing File.")
}
}
}
File类下的exists()方法是判断文件是否存在返回值是boolean
希望是你需要的。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)