❶ java中怎么把文件上传到服务器的指定路径
文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持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中怎么把文件上传到服务器的指定路径
String realpath = ServletActionContext.getServletContext().getRealPath("/upload") ;//获取服务器路径
String[] targetFileName = uploadFileName;
for (int i = 0; i < upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.File(upload[i], target);
//这是一个文件复制类File()里面就是IO操作,如果你不用这个类也可以自己写一个IO复制文件的类
}
其中private File[] upload;// 实际上传文件
private String[] uploadContentType; // 文件的内容类型
private String[] uploadFileName; // 上传文件名
这三个参数必须这样命名,因为文件上传控件默认是封装了这3个参数的,且在action里面他们应有get,set方法
❸ 用java怎么上传图片到项目指定的文件夹
你的意思是拷贝吗,还是上传到服务器什么的
import java.io.*;
/**
* 复制文件夹或文件夹
*/
public class CopyDirectory {
// 源文件夹
static String url1 = "f:/photos";
// 目标文件夹
static String url2 = "d:/tempPhotos";
public static void main(String args[]) throws IOException {
// 创建目标文件夹
(new File(url2)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(url1)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 复制文件
File(file[i],new File(url2+file[i].getName()));
}
if (file[i].isDirectory()) {
// 复制目录
String sourceDir=url1+File.separator+file[i].getName();
String targetDir=url2+File.separator+file[i].getName();
Directiory(sourceDir, targetDir);
}
}
}
// 复制文件
public static void File(File sourceFile,File targetFile)
throws IOException{
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff=new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff=new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len =inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
//关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 复制文件夹
public static void Directiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile=file[i];
// 目标文件
File targetFile=new
File(new File(targetDir).getAbsolutePath()
+File.separator+file[i].getName());
File(sourceFile,targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1=sourceDir + "/" + file[i].getName();
// 准备复制的目标文件夹
String dir2=targetDir + "/"+ file[i].getName();
Directiory(dir1, dir2);
}
}
}
}
❹ java ftp上传文件夹及子目录文件时,只能上传部分文件 急!
ftp上传我不知道··
如果是文件上传到服务器的话希望这代码能起到一定的作用·
在servlet里面写:
// 保存文件到服务器中
String fileName = null;
try {
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
List<FileItem> fileItems = upload.parseRequest(request);
Iterator<FileItem> iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField()) {
fileName = item.getName();
try {
item.write(new File(uploadPath + fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println("保存文件到服务器失败");
errorElement.setText(ErrorCode.VVLIVE_UPLOADFILD + "");
}
❺ java上传到指定文件夹问题
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
❻ 请问java文件上传到服务器的指定文件夹怎么写啊
你好像理会错了点东西。
上传是从客户端读取文件,通过流传输。服务器接收数据,并写入文件。
所以FileInputStream fis=new FileInputStream(fromPath);
这样的代码根本就有问题。
❼ java中文件上传 new File(文件路径)问题
通过 ”new FileInputStream(文件路径)“的形式进行上传即可。举例:
/**
* 加密文件
*
* @param fileName
* @param date
* @param plainFilePath 明文文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String encodeAESFileUploadByFtp(String plainFilePath, String fileName, String date,String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上传文件开始");
byte[] bytes = encodeAES(key, bos.toByteArray());
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Log.info("连接远程上传服务器"+CMBCUtil.CMBCHOSTNAME+":"+2021);
ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
// Log.info("连接远程上传服务器"+"192.168.54.106:"+2021);
// ftpClient.connect("192.168.54.106", 2021);
// ftpClient.login("hkrt-CMBCHK", "3OLJheziiKnkVcu7Sigz");
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
ftpClient.makeDirectory(date);
ftpClient.changeWorkingDirectory("/"+filepath+"/" + date);
}
}
Log.info("检查文件路径是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, is);
Log.info("加密上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/" + date);
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
❽ java怎么实现SFTP上传文件夹,包括整个目录
把文件枚举出来,一个一个地上传
❾ java获得上传文件的路径
commons-io下载地址:http://commons.apache.org/io/download_io.cgi
common-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);
Iterator items;
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 那就更简单一点了
❿ 用JAVA程序如何在D盘根目录中建立文件夹保存上传过来的文件,以及如何计算文件夹大小
这个是用框架做的用的Struts2需要你加框架和jsp页面的只能给你些代码自己看看了 其实也都通用的 package actions;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport{
private String username;
private File upload;
private String uploadFileName;
private String uploadContentType;
public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public File getUpload() {
return upload;
} public void setUpload(File upload) {
this.upload = upload;
} public String getUploadFileName() {
return uploadFileName;
} public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
} public String getUploadContentType() {
return uploadContentType;
} public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
} @Override
public String execute() throws Exception {
// TODO Auto-generated method stub
InputStream fin=new FileInputStream(upload);
String root=ServletActionContext.getRequest().getRealPath("upload");
//root获取上传文件的服务器目录;
//String root="d:/upload";
File file=new File(root,uploadFileName);//root的位置可以换成相对的路径
OutputStream fos=new FileOutputStream(file);
byte[] buffer=new byte[1024];
int len=0;
while((len=fin.read(buffer))>0)
{
fos.write(buffer,0,len);
}
fin.close();
fos.close();
return SUCCESS;
}
}