导航:首页 > 编程语言 > java上传方法代码

java上传方法代码

发布时间:2023-08-06 12:04:34

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

阅读全文

与java上传方法代码相关的资料

热点内容
python代码过长换行 浏览:697
欧冠直播哪个app画质最清楚 浏览:225
iphone6备份密码 浏览:365
微信打码赚钱安卓软件 浏览:608
苹果官换机买什么版本 浏览:979
visio数据模型怎么用 浏览:179
关于驾驶的app 浏览:92
多线程编程有什么特点 浏览:453
iso文件系统 浏览:116
苹果932拦截骚扰电话 浏览:765
盲盒开箱app有哪些 浏览:422
win10激活脚本之家 浏览:191
魔鬼作坊工具包 浏览:185
ae源文件下载 浏览:520
如何将照片内容转换成pdf文件 浏览:137
浙里办app如何更换手机号码 浏览:244
电子资料文件有哪些 浏览:241
猥琐猫表情教程 浏览:599
android音频文件格式 浏览:458
漫画脸app哪里可以下载 浏览:959

友情链接