當前位置:首頁 » 文件管理 » java文件上傳demo

java文件上傳demo

發布時間: 2022-08-30 02:03:39

1. 用java的三大框架實現文件的上傳下載,求代碼啊,最好是分為action,service,serv

package cn.itcast.struts2.demo1;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
* 完成文件上傳 (不是解析上傳內容,因為上傳內容 由fileUpload攔截器負責解析)
*
* @author seawind
*
*/
public class UploadAction extends ActionSupport {
// 接收上傳內容
// <input type="file" name="upload" />
private File upload; // 這里變數名 和 頁面表單元素 name 屬性一致
private String uploadContentType;
private String uploadFileName;

public void setUpload(File upload) {
this.upload = upload;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

@Override
public String execute() throws Exception {
if (upload == null) { // 通過xml配置 required校驗器 完成校驗
// 沒有上傳文件
return NONE;
}
// 將上傳文件 保存到伺服器端
// 源文件 upload
// 目標文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload") + "/" + uploadFileName);
// 文件復制 使用commons-io包 提供 工具類
FileUtils.File(upload, destFile);
return NONE;
}
}
多文件上傳
package cn.itcast.struts2.demo1;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
* 支持多文件上傳
*
* @author seawind
*
*/
public class MultiUploadAction extends ActionSupport {
// 接收多文件上傳參數,提供數組接收就可以了
private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;

public void setUpload(File[] upload) {
this.upload = upload;
}

public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}

public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}

@Override
public String execute() throws Exception {
for (int i = 0; i < upload.length; i++) {
// 循環完成上傳
File srcFile = upload[i];
String filename = uploadFileName[i];

// 定義目標文件
File destFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload" + "/" + filename));
FileUtils.File(srcFile, destFile);
}
return NONE;
}
}

2. 你好 可以幫我寫一個基於Java的 文件上傳下載的Demo 新手 學習中

importjava.io.*;
publicclassFileDemo{
publicstaticvoidmain(String[]args)throwsException{
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
System.out.println("請輸入本地要下載的文件路徑:");
Stringbd=in.readLine();
System.out.println("請輸入要下載保存的路徑以及文件名:");
Stringbc=in.readLine();
FileInputStreamfis=newFileInputStream(bd);
FileOutputStreamfos=newFileOutputSream(bc);
byte[]b=newbyte[1024];
intlen=0;
while((len=fis.read(b))!=-1){
fos.write(b,0,len);
}
System.out.println("文件下載成功");
fos.close();
fis.close();

}
}

3. java中怎樣上傳文件

Java代碼實現文件上傳

FormFilefile=manform.getFile();
StringnewfileName=null;
Stringnewpathname=null;
StringfileAddre="/numUp";
try{
InputStreamstream=file.getInputStream();//把文件讀入
StringfilePath=request.getRealPath(fileAddre);//取系統當前路徑
Filefile1=newFile(filePath);//添加了自動創建目錄的功能
((File)file1).mkdir();
newfileName=System.currentTimeMillis()
+file.getFileName().substring(
file.getFileName().lastIndexOf('.'));
ByteArrayOutputStreambaos=newByteArrayOutputStream();
OutputStreambos=newFileOutputStream(filePath+"/"
+newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
//建立一個上傳文件的輸出流
System.out.println(filePath+"/"+file.getFileName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=stream.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);//將文件寫入伺服器
}
bos.close();
stream.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}

4. 請問有java上傳文件到ftp伺服器的demo嗎,感激不盡

/**
* 依賴commons-net-3.4.jar, commons-io-2.4.jar
*/
public class FtpUtils {
/**
* 上傳
* @param host FTP地址
* @param port 埠ftp默認22,sftp默認23
* @param user ftp用戶名
* @param pwd ftp密碼
* @param destPath FTP文件保存路徑
* @param fileName ftp保存文件名稱
* @param file 需要上傳的文件
*/
public static void upload(String host, int port,String user, String pwd, String destPath, String fileName, File file){
FTPClient ftp = null;
InputStream fis = null;
try {
//1.建立連接
ftp = new FTPClient();
ftp.connect(host, port);
//2.驗證連接地址
int reply = ftp.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
return;
}
//3.登錄
ftp.login(user, pwd);
//設置上傳路徑、緩存、字元集、文件類型等
ftp.changeWorkingDirectory(destPath);
ftp.setBufferSize(1024);
ftp.setControlEncoding("UTF-8");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//4.上傳
fis = new FileInputStream(file);
ftp.storeFile(fileName, fis);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(fis);
try {
if(ftp.isAvailable()){
ftp.logout();
}
if(ftp.isConnected()){
ftp.disconnect();
}
//刪除上傳臨時文件
if(null != file && file.exists()){
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

5. JAVA怎麼把文件的上傳路徑存入資料庫,知道思路,具體怎麼實現SQL語句部分具體DEMO

突然阿發達 DSA ASD DSAEWE;LSKD ;Q W EWQ E WQE WQE WEM 'WFSWSDSADSADA

6. java實現文件上傳,代碼盡量簡潔~~~~~·

你說的2種方法都是很簡單的,參考網上的資料都不難做出,用io流做更是基礎中的基礎,我說下smartupload好了,有的人是直接寫在jsp上面,感覺比較亂,我一般都是寫在action裡面,打好jar包和配置後

SmartUpload mySmartUpload = new SmartUpload();

//如果是struts2.0或者webwork 則是mySmartUpload.initialize(ServletActionContext.getServletConfig(),ServletActionContext.getRequest(),ServletActionContext.getResponse());

mySmartUpload.initialize(servlet.getServletConfig(), request,response);
mySmartUpload.setTotalMaxFileSize(500000);
//如果上傳任意文件不設置mySmartUpload.setAllowedFilesList(文件後綴名)就可以了
mySmartUpload.upload();
for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
com.jspsmart.upload.File file = mySmartUpload.getFiles().getFile(i);
if (file.isMissing()) continue;
file.saveAs(保存的地址 + file.getFileName(),
su.SAVE_PHYSICAL);

7. java 文件上傳的代碼,盡量詳細一點。。。

// 這是我寫的一個方法,裡面只需要傳兩個參數就OK了,在任何地方調用此方法都可以文件上傳
/**
* 上傳文件
* @param file待上傳的文件
* @param storePath待存儲的路徑(該路徑還包括文件名)
*/
public void uploadFormFile(FormFile file,String storePath)throws Exception{
// 開始上傳
InputStream is =null;
OutputStream os =null;
try {
is = file.getInputStream();
os = new FileOutputStream(storePath);
int bytes = 0;
byte[] buffer = new byte[8192];
while ((bytes = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytes);
}
os.close();
is.close();
} catch (Exception e) {
throw e;
}
finally{
if(os!=null){
try{
os.close();
os=null;
}catch(Exception e1){
;
}
}
if(is!=null){
try{
is.close();
is=null;
}catch(Exception e1){
;
}
}
}
}

8. 用java實現文件的上傳與下載

1.下載簡單,無非是把伺服器上的文件或者資料庫中的BLob(或其他二進制型),用流讀出來,然後寫到客戶端即可,要注意 ContentType。

2.上傳,可以用Apache Commons Upload等開源工具,或者自己寫:
form要用enctype="multipart/form-data"
然後伺服器端也是用IO把客戶端提交的文件流讀入,然後寫到伺服器的文件系統或者資料庫里。不同的資料庫對Lob欄位操作可能有所不同,建議用Hibernate,JPA等成熟的ORM框架,可以不考慮資料庫細節。

9. java如何實現文件上傳

public static int transFile(InputStream in, OutputStream out, int fileSize) {
int receiveLen = 0;
final int bufSize = 1000;
try {
byte[] buf = new byte[bufSize];
int len = 0;
while(fileSize - receiveLen > bufSize)
{
len = in.read(buf);
out.write(buf, 0, len);
out.flush();
receiveLen += len;
System.out.println(len);
}
while(receiveLen < fileSize)
{
len = in.read(buf, 0, fileSize - receiveLen);
System.out.println(len);
out.write(buf, 0, len);
receiveLen += len;
out.flush();
}
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return receiveLen;
}
這個方法從InputStream中讀取內容,寫到OutputStream中。
那麼發送文件方,InputStream就是FileInputStream,OutputStream就是Socket.getOutputStream.
接受文件方,InputStream就是Socket.getInputStream,OutputStream就是FileOutputStream。
就OK了。 至於存到資料庫里嘛,Oracle里用Blob。搜索一下,也是一樣的。從Blob能獲取一個輸出流。

10. 怎麼用Java實現圖片上傳

下面這是servlet的內容:
package demo;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class DemoServlet extends HttpServlet {

private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {

public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小為:"+pContentLength+",當前已處理:"+pBytesRead);

}
});
//判斷提交上來的數據是否是上傳表單的數據
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//設置臨時儲存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//設置最大文件上傳值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//設置最大請求值(包含文件和表單數據)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}

try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上傳成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "錯誤信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}

}

下面是jsp的內容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉發的路徑改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
這段代碼可以實現普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳

熱點內容
酒商城源碼 發布:2024-10-13 01:58:54 瀏覽:135
我的世界伺服器圈地設計 發布:2024-10-13 01:46:16 瀏覽:217
配置升級到什麼型號好 發布:2024-10-13 01:38:35 瀏覽:195
面試java基礎 發布:2024-10-13 01:38:34 瀏覽:891
製作加密dvd 發布:2024-10-13 01:32:41 瀏覽:570
java批量發送簡訊 發布:2024-10-13 01:27:00 瀏覽:223
androidstring特殊 發布:2024-10-13 01:21:19 瀏覽:239
nginxphp配置 發布:2024-10-13 01:12:55 瀏覽:570
網路游戲Server編程 發布:2024-10-13 00:41:44 瀏覽:227
androidqq分組 發布:2024-10-13 00:41:09 瀏覽:20