导航:首页 > IDC知识 > java上传文件到本地服务器

java上传文件到本地服务器

发布时间:2020-12-20 10:55:05

1、java怎么实现上传文件到服务器

common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件

下面先介绍上传文件到服务器(多文件上传):

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

import java.util.regex.*;

import org.apache.commons.fileupload.*;


public class upload extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=GB2312";

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(CONTENT_TYPE);

PrintWriter out=response.getWriter();

try {

DiskFileUpload fu = new DiskFileUpload();

 // 设置允许用户上传文件大小,单位:字节,这里设为2m

 fu.setSizeMax(2*1024*1024);

 // 设置最多只允许在内存中存储的数据,单位:字节

 fu.setSizeThreshold(4096);

 // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

 fu.setRepositoryPath("c://windows//temp");

 //开始读取上传信息

 List fileItems = fu.parseRequest(request);

 // 依次处理每个上传的文件

 Iterator iter = fileItems.iterator();

//正则匹配,过滤路径取文件名

 String regExp=".+////(.+)$";

//过滤掉的文件类型

String[] errorType={".exe",".com",".cgi",".asp"};

 Pattern p = Pattern.compile(regExp);

 while (iter.hasNext()) {

 FileItem item = (FileItem)iter.next();

 //忽略其他不是文件域的所有表单信息

 if (!item.isFormField()) {

 String name = item.getName();

 long size = item.getSize();

 if((name==null||name.equals("")) && size==0)

 continue;

 Matcher m = p.matcher(name);

 boolean result = m.find();

 if (result){

 for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){

 if (m.group(1).endsWith(errorType[temp])){

 throw new IOException(name+": wrong type");

 }

 }

 try{

//保存上传的文件到指定的目录

//在下文中上传文件至数据库时,将对这里改写

 item.write(new File("d://" + m.group(1)));

out.print(name+"  "+size+"");

 }

 catch(Exception e){

 out.println(e);

 }

}

 else

 {

 throw new IOException("fail to upload");

 }

 }

 }

}

 catch (IOException e){

 out.println(e);

 }

 catch (FileUploadException e){

out.println(e);

 }

 

}

}

现在介绍上传文件到服务器,下面只写出相关代码:

以sql2000为例,表结构如下:

字段名:name  filecode

类型: varchar image

数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");

代码如下:

。。。。。。

try{

这段代码如果不去掉,将一同写入到服务器中

//item.write(new File("d://" + m.group(1)));

 

int byteread=0;

//读取输入流,也就是上传的文件内容

InputStream inStream=item.getInputStream();  

pstmt.setString(1,m.group(1));

pstmt.setBinaryStream(2,inStream,(int)size);

pstmt.executeUpdate();

inStream.close();

out.println(name+"  "+size+" ");

}

。。。。。。

这样就实现了上传文件至数据库

2、JAVA如何把本地文件上传到服务器。

这个你就要参考,java上传文件的相关资料了。
告诉你有现成的代码,你可以找写拷贝过去直接使用。

3、java 实现文件上传到另一台服务器,该怎么解决

上传本地文件代码
使用步骤如下:
1.调用AddFile函数添加本地文件,注意路径需要使用版双斜框(\\)
2.调用PostFirst函数开始上权传文件。
JavaScript code?<script type="text/javascript" language="javascript"> var fileMgr = new HttpUploaderMgr(); fileMgr.Load();//加载控件 window.onload = function() { fileMgr.Init();//初始化控件 //添加一个本地文件 fileMgr.AddFile("D:\\Soft\\QQ2010.exe"); fileMgr.PostFirst(); };</script>

4、java web 本地端上传文件到服务器端

Web文件来上传采用POST的方式,与POST提交表单不同源的是,上传文件需要设置FORM的enctype属性为multipart/form-data.由于上传的文件会比较大,因此需要设置该参数指定浏览器使用二进制上传。如果不设置,enctype属性默认为application/x-www-form-urlencoded,使用浏览器将使用ASCII向服务器发送数据,导致发送文件失败。
上传文件要使用文件域(<input type='file'/>,并把FORM的Enctype设置为multipart/form-data.

5、javaweb 怎么样将本地文件传输到远程服务器

可以通过JDK自带的API实现,如下代码:
package com.cloudpower.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* Java自带的API对FTP的操作
* @Title:Ftp.java
*/
public class Ftp {
/**
* 本地文件名
*/
private String localfilename;
/**
* 远程文件名
*/
private String remotefilename;
/**
* FTP客户端
*/
private FtpClient ftpClient;

/**
* 服务器连接
* @param ip 服务器IP
* @param port 服务器端口
* @param user 用户名
* @param password 密码
* @param path 服务器路径
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******连接服务器的两种方法*******/
//第一种方法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二种方法
ftpClient = new FtpClient(ip);

ftpClient.login(user, password);
// 设置成2进制传输
ftpClient.binary();
System.out.println("login success!");
if (path.length() != 0){
//把远程系统上的目录切换到参数path所指定的目录
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println("disconnect success");
} catch (IOException ex) {
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void upload(String localFile, String remoteFile) {
this.localfilename = localFile;
this.remotefilename = remoteFile;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//将远程文件加入输出流中
os = ftpClient.put(this.remotefilename);
//获取本地文件的输入流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//创建一个缓冲区
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("upload success");
} catch (IOException ex) {
System.out.println("not upload");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
is = ftpClient.get(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("download success");
} catch (IOException ex) {
System.out.println("not download");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String agrs[]) {

String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};

Ftp fu = new Ftp();
/*
* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
*/
fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");

//下载
for (int i = 0; i < filepath.length; i++) {
fu.download(filepath[i], localfilepath[i]);
}

String localfile = "E:\\号码.txt";
String remotefile = "/temp/哈哈.txt";
//上传
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}

6、JAVA如何把本地文件上传到服务器。

如果抄服务器开通了ftp服务,你的客户端可以实现一个ftp的客户端,通过ftp服务将文件上传到服务器的指定目录下,可以使用org.apache.commons.net.ftp.FTPClient这个类去实现,非常的简单,网上有很多现成的代码可以用

7、java指定文件,如何上传到服务器?

可以通过FTP的方式上传到指定服务器
希望我团的答案能给您一定的帮助~祝您早日解决问题~!
SOSO
~你敢告诉我,我的回答哪不符合规定了么??不告诉我原因我怎么改???

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、java 如何只通过后台把本地的图片上传的服务器上去

import java.io.*;
public class CopyIMG{
    public static void main(String[] args)throws Exception{
        File file = new File("C:xx.jpg");
        if(!file.exists())
            throw new RuntimeException("文件不存在..");
        FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[1024];
        int len = 0;
        FileOutputStream fos = new FileOutStream("要保存的服务器路径");
        while((len=is.read(b))!=-1){
            fos.write(b,0,len);
        }
        fos.close();
        fis.close();
    }
}

10、java如何上传本地文件夹到其他服务器(不一定是FTP服务器)

文件夹传输要用递归循环文件夹里面的内容,遇到一个文件夹就新建一专个文件夹,否则新建文属件,然后一个一个的用字节流传输(FileInputStream和FileOutputStream),不过这样效率会很低,

与java上传文件到本地服务器相关的知识