当前位置:首页 > 代码 > 正文

java文件上传到服务器代码(java 上传文件到服务器)

admin 发布:2022-12-19 22:36 130


本篇文章给大家谈谈java文件上传到服务器代码,以及java 上传文件到服务器对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

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.copyFile(upload[i], target);

//这是一个文件复制类copyFile()里面就是IO操作,如果你不用这个类也可以自己写一个IO复制文件的类

}

其中private File[] upload;// 实际上传文件

private String[] uploadContentType; // 文件的内容类型

private String[] uploadFileName; // 上传文件名

这三个参数必须这样命名,因为文件上传控件默认是封装了这3个参数的,且在action里面他们应有get,set方法

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

java后台文件上传到资源服务器上

package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * 上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 文件服务器的rul * @return 返回响应的内容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {

String result = null;

String BOUNDARY = "letv"; // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n";

String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try {

URL url = new URL(RequestURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setReadTimeout(TIME_OUT);

conn.setConnectTimeout(TIME_OUT);

conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

java上传文件代码

public class FileUpLoad extends ActionSupport{

//"多文件上传就用list就可以了private ListFile file;"

private File file;

//上传文本的name

public File getFile() {

return file;

}

public void setFile(File file) {

this.file = file;

}

private String fileContentType;

//上传的文件类型。

public String getFileContentType() {

return fileContentType;

}

public void setFileContentType(String fileContentType) {

this.fileContentType = fileContentType;

}

//获取上传文件的名称

private String fileFileName;

public String getFileFileName() {

return fileFileName;

}

public void setFileFileName(String fileFileName) {

this.fileFileName = fileFileName;

}

public String upload() throws Exception

{

//获取文件上传路径

String root=ServletActionContext.getRequest().getRealPath("/upload");

InputStream is=new FileInputStream(file);

String.substring(fileFileName.indexOf("."));//截取上传文件的后缀。便于新定义名称。.jpg

System.out.println(name);

File descFile=new File(root,新定义的文件名称+fileFileName.indexOf("."));

OutputStream os=new FileOutputStream(descFile);

byte[] buffer=new byte[1024];

int length=0;

while(-1!=(length=(is.read(buffer))))

{

os.write(buffer, 0, length);

}

is.close();

os.close();

return SUCCESS;

}

}

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;tempERRORTYPE.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+" ");

      }

。。。。。。

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

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

/**

* Java自带的API对FTP的操作

* @Title:

*/

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

}

}

java文件上传到服务器代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java 上传文件到服务器、java文件上传到服务器代码的信息别忘了在本站进行查找喔。

版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;

本文地址:http://ahzz.com.cn/post/27973.html


取消回复欢迎 发表评论:

分享到

温馨提示

下载成功了么?或者链接失效了?

联系我们反馈

立即下载