Ⅰ 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 可以获取上传的文件名。
Ⅱ 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();
}
Ⅲ 怎么用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>
这段代码可以实现普通的文件上传,有大小限制,上传普通的图片肯定没问题,别的一些小的文件也能传
Ⅳ 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能获取一个输出流。
Ⅳ java可以上传什么格式的文件
理论上所有格式的文件都可以上传!
Ⅵ 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);
}
}
}
}
备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。
Ⅶ 如何用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);
}
}
}
}
Ⅷ 如何实现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;
}
}
Ⅸ java实现文件的上传和下载
用输出流 接受 一个下载地址的网络流
然后将这个输出流 保存到本地一个文件 后缀与下载地址的后缀相同··
上传的话 将某个文件流 转成字节流 上传到某个webservice方法里
-------要代码来代码
URL url=new URL("http://www..com/1.rar");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");
这是下载 上传太麻烦就不给写了