当前位置:首页 » 文件管理 » 上传文件java

上传文件java

发布时间: 2022-02-05 13:08:15

A. 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();
}

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

  • }

  • 。。。。。。

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

C. java 上传附件实现方法

上传附件,实际上就是将文件存储到远程服务器,进行临时存储。举例:
**
* 上传文件
*
* @param fileName
* @param plainFilePath 文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByftp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上传文件开始");
Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("检查文件路径是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。

D. 怎么用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>
这段代码可以实现普通的文件上传,有大小限制,上传普通的图片肯定没问题,别的一些小的文件也能传

E. 如何实现java 流式文件上传

@Controller
public class UploadController extends BaseController {

private static final Log log = LogFactory.getLog(UploadController.class);
private UploadService uploadService;
private AuthService authService;

/**
* 大文件分成小文件块上传,一次传递一块,最后一块上传成功后,将合并所有已经上传的块,保存到File Server
* 上相应的位置,并返回已经成功上传的文件的详细属性. 当最后一块上传完毕,返回上传成功的信息。此时用getFileList查询该文件,
* 该文件的uploadStatus为2。client请自行处理该状态下文件如何显示。(for UPS Server)
*
*/
@RequestMapping("/core/v1/file/upload")
@ResponseBody
public Object upload(HttpServletResponse response,
@RequestParam(value = "client_id", required = false) String appkey,
@RequestParam(value = "sig", required = false) String appsig,
@RequestParam(value = "token", required = false) String token,
@RequestParam(value = "uuid", required = false) String uuid,
@RequestParam(value = "block", required = false) String blockIndex,
@RequestParam(value = "file", required = false) MultipartFile multipartFile,
@RequestParam Map<String, String> parameters) {

checkEmpty(appkey, BaseException.ERROR_CODE_16002);
checkEmpty(token, BaseException.ERROR_CODE_16007);
checkEmpty(uuid, BaseException.ERROR_CODE_20016);
checkEmpty(blockIndex, BaseException.ERROR_CODE_20006);
checkEmpty(appsig, BaseException.ERROR_CODE_10010);
if (multipartFile == null) {
throw new BaseException(BaseException.ERROR_CODE_20020);// 上传文件不存在
}
Long uuidL = parseLong(uuid, BaseException.ERROR_CODE_20016);
Integer blockIndexI = parseInt(blockIndex, BaseException.ERROR_CODE_20006);

Map<String, Object> appMap = getAuthService().validateSigature(parameters);

AccessToken accessToken = CasUtil.checkAccessToken(token, appMap);
Long uid = accessToken.getUid();
String bucketUrl = accessToken.getBucketUrl();
// 从上传目录拷贝文件到工作目录
String fileAbsulutePath = null;
try {
fileAbsulutePath = this.File(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
} catch (IOException ioe) {
log.error(ioe.getMessage(), ioe);
throw new BaseException(BaseException.ERROR_CODE_20020);// 上传文件不存在
}
File uploadedFile = new File(Global.UPLOAD_TEMP_DIR + fileAbsulutePath);
checkEmptyFile(uploadedFile);// file 非空验证

Object rs = uploadService.upload(uuidL, blockIndexI, uid, uploadedFile, bucketUrl);
setHttpStatusOk(response);
return rs;
}

// TODO 查看下这里是否有问题
// 上传文件非空验证
private void checkEmptyFile(File file) {
if (file == null || file.getAbsolutePath() == null) {
throw new BaseException(BaseException.ERROR_CODE_20020);// 上传文件不存在
}
}

/**
* 写文件到本地文件夹
*
* @throws IOException
* 返回生成的文件名
*/
private String File(InputStream inputStream, String fileName) {
OutputStream outputStream = null;
String tempFileName = null;
int pointPosition = fileName.lastIndexOf(".");
if (pointPosition < 0) {// myvedio
tempFileName = UUID.randomUUID().toString();// 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26
} else {// myvedio.flv
tempFileName = UUID.randomUUID() + fileName.substring(pointPosition);// 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26.flv
}
try {
outputStream = new FileOutputStream(Global.UPLOAD_TEMP_DIR + tempFileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
return tempFileName;
} catch (IOException ioe) {
// log.error(ioe.getMessage(), ioe);
throw new BaseException(BaseException.ERROR_CODE_20020);// 上传文件不存在
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}

}

}

/**
* 测试此服务是否可用
*
* @param response
* @return
* @author zwq7978
*/
@RequestMapping("/core/v1/file/testServer")
@ResponseBody
public Object testServer(HttpServletResponse response) {
setHttpStatusOk(response);
return Global.SUCCESS_RESPONSE;
}

public UploadService getUploadService() {
return uploadService;
}

public void setUploadService(UploadService uploadService) {
this.uploadService = uploadService;
}

public void setAuthService(AuthService authService) {
this.authService = authService;
}

public AuthService getAuthService() {
return authService;
}

}

F. 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能获取一个输出流。

G. JAVA WEB文件上传步骤

JAVA WEB文件上传步骤如下:
实现 Web 开发中的文件上传功能,两个操作:在 Web 页面添加上传输入项,在 Servlet 中读取上传文件的数据并保存在本地硬盘中。
1、Web 端上传文件。在 Web 页面中添加上传输入项:<input type="file"> 设置文件上传输入项时应注意:(1) 必须设置 input 输入项的 name 属性,否则浏览器将不会发送上传文件的数据。(2) 必须把 form 的 enctype 属性设为 multipart/form-data,设置该值后,浏览器在上传文件时,将把文件数据附带在 http 请求消息体中,并使用 MIME 协议对上传文件进行描述,以方便接收方对上传数据进行解析和处理。(3) 表单提交的方式要是 post
2、服务器端获取文件。如果提交表单的类型为 multipart/form-data 时,就不能采用传统方式获取数据。因为当表单类型为 multipart/form-data 时,浏览器会将数据以 MIME 协议的形式进行描述。如果想在服务器端获取数据,那么我们必须采用获取请求消息输入流的方式来获取数据。
3、Apache-Commons-fileupload。为了方便用户处理上传数据,Apache 提供了一个用来处理表单文件上传的开源组建。使用 Commons-fileupload 需要 Commons-io 包的支持。
4、fileuplpad 组建工作流程
(1)客户端将数据封装在 request 对象中。
(2)服务器端获取到 request 对象。
(3)创建解析器工厂 DiskFileItemFactory 。
(4)创建解析器,将解析器工厂放入解析器构造函数中。之后解析器会对 request 进行解析。
(5)解析器会将每个表单项封装为各自对应的 FileItem。
(6)判断代表每个表单项的 FileItem 是否为普通表单项 isFormField,返回 true 为普通表单项。
(7)如果是普通表单项,通过 getFieldName 获取表单项名,getString 获得表单项值。
(8)如果 isFormField 返回 false 那么是用户要上传的数据,可以通过 getInputStream 获取上传文件的数据。通过getName 可以获取上传的文件名。

H. Java文件上传的几种方式

1、通过Servlet类上传
2、通过Struts框架实现上传
ITJOB学到两种方式

I. 如何用java程序实现上传文件到指定的URL地址

参考代码如下:
import java.io.*;
/**
* 复制文件夹或文件夹
*/
public class CopyDirectory {
// 源文件夹
static String url1 = "f:/photos";
// 目标文件夹
static String url2 = "d:/tempPhotos";
public static void main(String args[]) throws IOException {
// 创建目标文件夹
(new File(url2)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(url1)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 复制文件
File(file[i],new File(url2+file[i].getName()));
}
if (file[i].isDirectory()) {
// 复制目录
String sourceDir=url1+File.separator+file[i].getName();
String targetDir=url2+File.separator+file[i].getName();
Directiory(sourceDir, targetDir);
}
}
}
// 复制文件
public static void File(File sourceFile,File targetFile)
throws IOException{
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff=new BufferedInputStream(input);

// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff=new BufferedOutputStream(output);

// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len =inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();

//关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 复制文件夹
public static void Directiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile=file[i];
// 目标文件
File targetFile=new
File(new File(targetDir).getAbsolutePath()
+File.separator+file[i].getName());
File(sourceFile,targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1=sourceDir + "/" + file[i].getName();
// 准备复制的目标文件夹
String dir2=targetDir + "/"+ file[i].getName();
Directiory(dir1, dir2);
}
}
}
}

热点内容
怎样在我的世界重建服务器 发布:2024-10-22 23:37:10 浏览:355
安卓手机如何使用手写功能 发布:2024-10-22 23:19:16 浏览:351
手机壁纸上传 发布:2024-10-22 23:13:51 浏览:772
oracle数据库迁移方案 发布:2024-10-22 23:10:53 浏览:384
七牛云存储java上传 发布:2024-10-22 23:10:49 浏览:236
kvm编译原理 发布:2024-10-22 22:57:41 浏览:441
qq密码情侣改成什么最好 发布:2024-10-22 22:55:48 浏览:809
linux安装cuda 发布:2024-10-22 22:32:07 浏览:487
编译和链接的键 发布:2024-10-22 22:21:01 浏览:115
java数组的实现 发布:2024-10-22 22:18:15 浏览:331