導航:首頁 > 文件處理 > javafile上傳文件夾

javafile上傳文件夾

發布時間:2022-06-25 00:43:07

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;
}

}

閱讀全文

與javafile上傳文件夾相關的資料

熱點內容
javaweb程序設計郭 瀏覽:247
gm聲望命令 瀏覽:484
pdf轉換器電腦版免費 瀏覽:41
解壓歌曲什麼歌最好 瀏覽:151
諾貝爾pdf 瀏覽:967
雲伺服器快速安裝系統原理 瀏覽:788
蘋果騰訊管家如何恢復加密相冊 瀏覽:115
手機軟體反編譯教程 瀏覽:858
sqlserver編程語言 瀏覽:650
gpa國際標准演算法 瀏覽:238
伺服器編程語言排行 瀏覽:947
怎麼下載快跑app 瀏覽:966
小紅書app如何保存視頻 瀏覽:172
如何解開系統加密文件 瀏覽:811
linux切換root命令 瀏覽:283
c編譯之後界面一閃而過怎麼辦 瀏覽:881
怎麼看ic卡是否加密 瀏覽:726
lgplc編程講座 瀏覽:809
cnc手動編程銑圓 瀏覽:724
cad中幾種命令的意思 瀏覽:328