1. java中通過按鈕"上傳"打開上傳對話框,選擇文件後把地址顯示在一個JTextField中,如何用代碼實現呢
package test;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class Win extends JFrame {
JButton jb = new JButton("上傳");
public Win() {
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
if(jfc.showOpenDialog(Win.this)==JFileChooser.APPROVE_OPTION ){//解釋下這里,彈出個對話框,可以選擇要上傳的文件,如果選擇了,就把選擇的文件的絕對路徑列印出來,有了絕對路徑,通過JTextField的settext就能設置進去了,那個我沒寫
System.out.println(jfc.getSelectedFile().getAbsolutePath());
}
}
});
//這下面的不用在意 一些設置
add(jb);
setLayout(new FlowLayout());
setSize(480, 320);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}
省略了main函數那一段 相信你能看得懂
2. 求JAVA上傳圖片代碼
package com;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.jspsmart.upload.*;
public class uploadfiles extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
//使用了一個第三方的組件,存放在web-inf/lib下
response.setContentType("text/html;charset=GB2312");
//由於SmartUpload的初始化方法需要pageContext,所以我們在servlet中得到他
//為了得到pageConext要首先得到JspFactory的實例
//通過JspFactory的實例的getPageContext方法得到pageConext的實例
JspFactory jf = null;
//得到JspFactory的實例
jf=JspFactory.getDefaultFactory();
/*
getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
java.lang.String errorPageURL,
boolean needsSession,
int buffer,
boolean autoflush)
*/
PageContext pageContext=jf.getPageContext(this,request,response,null,true,8192,true);
try
{
//實例化SmartUpload
SmartUpload mySmartUpload=new SmartUpload();
//初始化SmartUpload的實例,需要PageContext的實例
mySmartUpload.initialize(pageContext);
//設定最大上傳的位元組數,其實可以不進行設定,表示上傳的文件沒有大小限制
//mySmartUpload.setTotalMaxFileSize(10000000);
mySmartUpload.upload();
//下面是單文件上傳
//上傳的文件以com.jspsmart.upload.File 代表,如果文件名稱重復,則進行覆蓋
com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);
String upLoadFileName=file.getFileName();
//調用com.jspsmart.upload.File實例的saveas的方法保存文件,此時的文件名即是
//保存到伺服器上的文件名
file.saveAs("/upload/"+upLoadFileName);
Request req =
Text t = .....;
t.setUpload(upLoadFileName);
t.set.....(req);
}
catch(SmartUploadException e)
{
System.out.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
doGet(request,response);
}
}
3. 怎麼用Java實現FTP上傳
package com.sinosoft.sepmis.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
* Java自帶的API對FTP的操作
* @Title:Ftp.java
* @author: shanhong
*/
public class FtpUtil {
/**
* Description: 向FTP伺服器上傳文件
* @param url FTP伺服器hostname
* @param port FTP伺服器埠,如果默認埠請寫-1
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param path FTP伺服器保存目錄
* @param filename 上傳到FTP伺服器上的文件名
* @param input 輸入流
* @return 成功返回true,否則返回false
*/
public static boolean uploadFile(String url, int port, String username, String password, String path,
String filename, InputStream input) throws Exception
{
boolean success = false;
FTPClient ftp = new FTPClient();
try
{
int reply;
// 連接FTP伺服器
if (port > -1)
{
ftp.connect(url, port);
}
else
{
ftp.connect(url);
}
// 登錄FTP
ftp.login(username, password);
reply = ftp.getReplyCode();
System.out.println(reply);
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
}
catch (IOException e)
{
success = false;
throw e;
}
finally
{
if (ftp.isConnected())
{
try
{
ftp.disconnect();
}
catch (IOException e)
{
throw e;
}
}
}
return success;
}
public static void main(String agrs[]) {
try {
File file = new File("E:\\1.txt");
FileInputStream in = new FileInputStream(file);
/*
* 使用默認的埠號、用戶名、密碼以及根目錄連接FTP伺服器
*/
//返回true上傳成功,否則上傳失敗
// FtpUtil.uploadFile("192.168.61.209", -22, "instiaci", "instiaci", "/db2home/instiaci/personal/shanhz","2.txt",in);
//「sinopipi/IC/tkk"目錄要是已經存在的目錄
FtpUtil.uploadFile("192.168.61.104", 22, "administrator", "123456", "/sinopipi/IC","6.txt",in);
} catch (Exception e) {
e.printStackTrace();
}
}
}
說明:所需的jar包是commons-net-2.0.jar
4. java實現文件上傳,代碼盡量簡潔~~~~~·
一個SpringMVC的文件上傳示例
1、jsp頁面代碼
<%@pagepageEncoding="utf-8"%>
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>上傳圖片</title>
</head>
<body>
<formaction="message.do">
<inputtype="text"name="test"value="Submit"/><inputtype="submit"
value="Submit"/>
</form>
<formaction="upload.do"method="post"enctype="multipart/form-data">
<inputtype="file"name="file"/><inputtype="submit"value="Submit"/>
</form>
</body>
</html>
2、action代碼
@RequestMapping(value="/upload.do")
publicStringupload(@RequestParam(value="file",required=false)MultipartFilefile,HttpServletRequestrequest,
ModelMapmodel){
Stringpath="/Users/xieyuhai/Desktop";//更換一下路徑
StringfileName=file.getOriginalFilename();
//StringfileName=newDate().getTime()+".jpg";
System.out.println(path);
FiletargetFile=newFile(path,fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try{
file.transferTo(targetFile);
}catch(Exceptione){
e.printStackTrace();
}
model.addAttribute("resultUrl",request.getContextPath()+"/upload/"+fileName);
return"result";
}
5. 求java web 實現的文件上傳代碼 用開發環境是myeclipse
這個例子
下載:commons-fileUpload-1.2 的jar包:http://www.apache.org/commons/,同時可以把commons-IO的jar包一起下載,以後會用到的。
1、上傳的前台頁面:
<%@pagelanguage="java"import="java.util.*"contentType="text/html;charset=gbk" pageEncoding="gbk"%> <html> <body>
<form action="MultipartTestServlet" enctype="multipart/form-data" method="post">
<input type="text" name="username" /><br /> <input type="file" name="myfile" /><br/> <input type="file" name="myfile" /><br/> <input type="submit" /> </form> </body> </html>
2、上傳的後台代碼:
後台代碼是個servlet,很簡單咯,覺得比ASP利用組件還簡單。呵呵 package upload;
import java.io.File;
import java.io.IOException; import java.util.ArrayList
; import java.util.Iterator; 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.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
public class MultipartTestServlet extends HttpServlet {
public MultipartTestServlet() { super(); }
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設置request編碼,主要是為了處理普通輸入框中的中文問題 request.setCharacterEncoding("gbk");
//這里對request進行封裝,RequestContext提供了對request多個訪問方法 RequestContext requestContext = new ServletRequestContext(request); //判斷表單是否是Multipart類型的。這里可以直接對request進行判斷,不過已經以前的用法了
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory(); //設置文件的緩存路徑
factory.setRepository(new File("c:/tmp/"));
ServletFileUpload upload = new ServletFileUpload(factory); //設置上傳文件大小的上限,-1表示無上限 upload.setSizeMax(100*1024*1024); List items = new ArrayList(); try {
//上傳文件,並解析出所有的表單欄位,包括普通欄位和文件欄位 items = upload.parseRequest(request); } catch (FileUploadException e1) {
System.out.println("文件上傳發生錯誤" + e1.getMessage()); }
//下面對每個欄位進行處理,分普通欄位和文件欄位 Iterator it = items.iterator(); while(it.hasNext()){
FileItem fileItem = (FileItem) it.next(); //如果是普通欄位
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk")); }else{
System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + fileItem.isInMemory() + " " + fileItem.getContentType() + " " + fileItem.getSize());
//保存文件,其實就是把緩存里的數據寫到目標路徑下 if(fileItem.getName()!=null && fileItem.getSize()!=0){ File fullFile = new File(fileItem.getName());
File newFile = new File("c:/temp/" + fullFile.getName()); try {
fileItem.write(newFile); } catch (Exception e) { e.printStackTrace(); } }else{
System.out.println("文件沒有選擇 或 文件內容為空"); } } } } } }
3、編譯和配置servlet
先設置classpath,使它包含commons-fileUpload的jar包路徑,然後進行編譯即可,注意這里的包路徑。
然後打開站點下的web-inf路徑下的web.xml,在裡面添加: <servlet>
<servlet-name>MultipartTestServlet</servlet-name>
<servlet-class>upload.MultipartTestServlet</servlet-class> </servlet> <servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>helloApp.DispatcherServlet</servlet-class> </servlet>
好了,現在就可以文件上傳了,不過運行之前記得在c:/下新建tmp和temp文件夾,別忘了,不然程序會報告錯誤的。
6. 在java中,我要寫上傳文件,代碼我該怎麼寫,回答者請把例題代碼寫上注釋!
是寫web程序吧,應該以二進制流的形式上傳,下面是servlet的文件上傳 ServletInputStream sis=request.getInputStream(); String filePath=this.getServletContext().getRealPath("/body.txt"); FileOutputStream fos=new FileOutputStream(filePath); byte[] buf=new byte[1024]; //read方法返回值表示實際讀取到的內容的位元組數,-1表示已經到達結尾處 int len=sis.read(buf,0,1024); while(len!=-1){ fos.write(buf,0,len); len=sis.read(buf,0,1024); } fos.close(); sis.close();
7. 誰能說說java批量上傳文件的原理,並且給個例子吧 謝了
剛學完多文件上傳,希望對你有幫助。
多文件上傳,就是把多個文件一起傳到指定的位置,他和單文件上傳類似,只需要改動幾個地方而已即可。首先是上傳頁面,由於要上傳多個文件,所以就必須有多個供用戶選擇的文件框,然後修改Action,把action中屬性的類型修改為list。
action如下:
public class UploadActionMany extends ActionSupport{
private List<File> upload;
private List<String> uploadFileName;
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.print(upload.size());
if(upload!=null){
for (int i = 0; i < upload.size(); i++) {
InputStream is=new FileInputStream(upload.get(i)); OutputStream os=new FileOutputStream("d:\\upload\\"+getUploadFileName().get(i)); byte buffer[]=new byte[1024];
int count=0;
while((count=is.read(buffer))>0){
os.write(buffer,0,count);
}
os.close();
is.close();
}
}
return SUCCESS;
}
省略set和get方法
jsp如下:
<html>
<head>
<title>文件上傳</title>
</head>
<body>
<s:form action="upload.action" method="post" enctype="multipart/form-data"> <s:file name="upload" label="上傳的文件一"></s:file>
<s:file name="upload" label="上傳的文件二"></s:file>
<s:file name="upload" label="上傳的文件三"></s:file>
<s:submit value="上傳"></s:submit>
</s:form>
</body>
</html>
希望對你有幫助,打代碼不容易啊,記得給點分
8. 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();
}
9. 前台js 後台java 怎麼上傳文件
可以用Uploadify這個插件進行上傳
參考網址:
http://www.uploadify.com/
http://www.blogjava.net/yangxiang/archive/2009/07/29/288888.html
前台綁定:
$(document).ready(function() {
$("#uploadify").uploadify({
'uploader' : 'uploadify.swf',
'script' : 'servlet/Upload',
'cancelImg' : 'images/cancel.png',
'folder' : 'uploads',
'queueID' : 'fileQueue',
'auto' : false,
'multi' : true,
'simUploadLimit' : 2,
'buttonText' : 'BROWSE'
});
});
後台:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String savePath = this.getServletConfig().getServletContext()
.getRealPath("");
savePath = savePath + "/uploads/";
File f1 = new File(savePath);
System.out.println(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
return;
}
Iterator<FileItem> it = fileList.iterator();
String name = "";
String extName = "";
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {
name = item.getName();
long size = item.getSize();
String type = item.getContentType();
System.out.println(size + " " + type);
if (name == null || name.trim().equals("")) {
continue;
}
//擴展名格式:
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf("."));
}
File file = null;
do {
//生成文件名:
name = UUID.randomUUID().toString();
file = new File(savePath + name + extName);
} while (file.exists());
File saveFile = new File(savePath + name + extName);
try {
item.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.getWriter().print(name + extName);
}