文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持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()
}
java文件中获得路径Thread.currentThread().getContextClassLoader().getResource("") //获得资源文件(.class文件)所在路径
ClassLoader.getSystemResource("")
Class_Name.class.getClassLoader().getResource("")
Class_Name.class .getResource("/")
Class_Name.class .getResource("") // 获得当前类所在路径
System.getProperty("user.dir") // 获得项目根目录的绝对路径
System.getProperty("java.class.path")//得到类路径和包路径
打印输出依次如下:
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/
file:/F:/work_litao/uri_test/WebContent/WEB-INF/classes/com/xml/imp/
F:\work_litao\uri_test
F:\work_litao\uri_test\WebContent\WEB-INF\classesF:\work_litao\uri_test\WebContent\WEB-INF\lib\dom4j.jar
2、 JSP中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getRequestURI()
文件的绝对路径 :application.getRealPath(request.getRequestURI())
当前web应用的绝对路径 :application.getRealPath("/")
取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent()
commons-io下载地址:http://commons.apache.org/io/download_io.cgicommon-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。
该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。
下载后解压zip包,将commons-fileupload.jar,和commons-io里面后缀为jar复制到你的项目的webapp\WEB-INF\lib\下,如果目录不存在请自建目录。
这个项目是用来上传文件,文件路径为workspace\项目名称\build\weboutput\file\项目下,如果没有该文件夹请创建一个。否则会发生找不到路径的情况
import java.io.File
import java.io.IOException
import java.io.PrintWriter
import java.util.Iterator
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.FileItemFactory
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
/**
* Servlet implementation class FileUpload
*/
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L
/**
* @see HttpServlet#HttpServlet()
*/
public FileUpload() {
super()
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//判断提交过来的表单是否为文件上传菜单
boolean isMultipart= ServletFileUpload.isMultipartContent(request)
if(isMultipart){
//构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory()
ServletFileUpload upload = new ServletFileUpload(factory)
Iteratoritems
try{
//解析表单中提交的所有文件内容
items=upload.parseRequest(request).iterator()
while(items.hasNext()){
FileItem item = (FileItem) items.next()
if(!item.isFormField()){
//取出上传文件的文件名称
String name = item.getName()
//取得上传文件以后的存储路径
String fileName=name.substring(name.lastIndexOf('\\')+1,name.length())
//上传文件以后的存储路径
String path= request.getRealPath("file")+File.separatorChar+fileName
//上传文件
File uploaderFile = new File(path)
item.write(uploaderFile)
//打印上传成功信息
response.setContentType("text/html")
response.setCharacterEncoding("GB2312")
PrintWriter out = response.getWriter()
out.print("<font size='2'>上传文件为:"+name+"<br>保存的地址为"+path+ "</font>")
}
}
}catch(Exception e){
e.printStackTrace()
}
}
}
}
http://blog.163.com/lin305_gf/blog/static/969524402011718102116625/
这是给你转载的网易博客的
servlet上传文件
如果你是用的 框架 比如struts2 那就更简单一点了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)