图片上传和文件上传本质上是一样的,图片本身也是文件。文件上传就是将图片上传到服务器,方式虽然有很多,但底层的实现都是文件的读写操作。

注意事项

1.form表单一定要写属性enctype="multipart/form-data"

2.为了能保证文件能上传成功file控件的name属性值要和你提交的控制层变量名一致,

例如空间名是file那么你要在后台这样定义

private File file; //file控件名

private String fileContentType;//图片类型

private String fileFileName; //文件名

1.jsp页面

<%@ 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">
<meta http-equiv="pragma" content="no-cache" />
<base target="_self">
<title>文件上传</title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" value="file">
<input type="submit" value="确定">
</form>
</body>
</html>

1.页面数据需要提交的Controller

package com.cpsec.tang.chemical.action;

import java.io.File;
import java.io.IOException;
import java.util.Random; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller; import com.cpsec.tang.chemical.biz.LunboBiz;
import com.cpsec.tang.chemical.entity.Image;
import com.opensymphony.xwork2.ActionSupport; @Controller("lunboAction")
public class LunboAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
@Resource(name="lunboBiz")
private LunboBiz lunboBiz;
private Image image;
private File file; //file控件名
private String fileContentType;//图片类型
private String fileFileName; //文件名
private Integer number; public String findImage(){
image=lunboBiz.findImage();
return SUCCESS;
} public String alterImage(){
image=lunboBiz.findImage();
return SUCCESS;
} public String alterImage1(){
HttpServletRequest request = ServletActionContext.getRequest();
String root = request.getRealPath("/upload");//图片要上传到的服务器路径
String names[]=fileFileName.split("\\.");
String fileName="";
if(names.length>=1){
fileName=getRandomString(20)+"."+names[names.length-1];
}
String picPath="upload/"+fileName;//图片保存到数据库的路径
File file1=new File(root);
try {
FileUtils.copyFile(file, new File(file1,fileName));
}
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
} /*获取一条随机字符串*/
public String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
} }

这是通过复制的方式上传文件,还有其他方式

方法二

@Controller("contractAction")
public class ContractAction extends ActionSupport { private final static String UPLOADDIR = "/files";//文件上传的路径,在webContent下建立
private File file; //input控件名一定为file
//上传文件名集合
private String fileFileName;
//上传文件内容类型集合
private String fileContentType; private String filename; public String upload() throws FileNotFoundException, IOException{
String path=uploadFile();//文件保存数据库的路径 return SUCCESS;
} //执行上传功能
@SuppressWarnings("deprecation")
public String uploadFile() throws FileNotFoundException, IOException {
try {
InputStream in = new FileInputStream(file);
String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);
File fileLocation = new File(dir);
//此处也可以在应用根目录手动建立目标上传目录
if(!fileLocation.exists()){
boolean isCreated = fileLocation.mkdir();
if(!isCreated) {
//目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。
return null;
}
}
// this.setFileFileName(getRandomString(20));
String[] Name=this.getFileFileName().split("\\.");
String fileName=getRandomString(20)+"."+Name[Name.length-1];
this.setFileFileName(fileName);
System.out.println(fileName);
File uploadFile = new File(dir, fileName);
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
return UPLOADDIR.substring(1)+"\\"+fileFileName;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
} public static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<length;i++){
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
} }

除了单图上传还有多图上传,原理都是一样的

package com.cpsec.tang.chemical.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport; /**
* 多文件上传
*/
public class FilesUploadAction extends ActionSupport {
//上传文件存放路径
private final static String UPLOADDIR = "/upload";
//上传文件集合
private List<File> file;
//上传文件名集合
private List<String> fileFileName;
//上传文件内容类型集合
private List<String> fileContentType; public List<File> getFile() {
return file;
} public void setFile(List<File> file) {
this.file = file;
} public List<String> getFileFileName() {
return fileFileName;
} public void setFileFileName(List<String> fileFileName) {
this.fileFileName = fileFileName;
} public List<String> getFileContentType() {
return fileContentType;
} public void setFileContentType(List<String> fileContentType) {
this.fileContentType = fileContentType;
} public String uploadform() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
String webpath=null;//上传路径
for (int i = 0; i < file.size(); i++) {
//循环上传每个文件
uploadFile(i);
webpath="upload/"+this.getFileFileName().get(i);
}
return "SUCCESS";
} //执行上传功能
private String uploadFile(int i) throws FileNotFoundException, IOException {
try { InputStream in = new FileInputStream(file.get(i));
String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);
File fileLocation = new File(dir);
//此处也可以在应用根目录手动建立目标上传目录
if(!fileLocation.exists()){
boolean isCreated = fileLocation.mkdir();
if(!isCreated) {
//目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。
return null;
}
}
String fileName=this.getFileFileName().get(i);
File uploadFile = new File(dir, fileName);
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
return uploadFile.toString();
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}

java web图片上传和文件上传的更多相关文章

  1. [原创]java WEB学习笔记49:文件上传基础,基于表单的文件上传,使用fileuoload 组件

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  2. [原创]java WEB学习笔记50:文件上传案例

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  3. 使用.NET框架、Web service实现Android的文件上传(二)

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYUAAAKpCAIAAADcx6fPAAAgAElEQVR4nOydd1hT5+LHg1attbfr1t ...

  4. springboot整合ueditor实现图片上传和文件上传功能

    springboot整合ueditor实现图片上传和文件上传功能 写在前面: 在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作: springboot+layui 整合百度富文本 ...

  5. Web攻防系列教程之文件上传攻防解析(转载)

    Web攻防系列教程之文件上传攻防解析: 文件上传是WEB应用很常见的一种功能,本身是一项正常的业务需求,不存在什么问题.但如果在上传时没有对文件进行正确处理,则很可能会发生安全问题.本文将对文件上传的 ...

  6. 一个简单的QQ隐藏图生成算法 通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传

    一个简单的QQ隐藏图生成算法   隐藏图不是什么新鲜的东西,具体表现在大部分社交软件中,预览图看到的是一张图,而点开后看到的又是另一张图.虽然很早就看到过这类图片,但是一直没有仔细研究过它的原理,今天 ...

  7. 百度开源富文本编辑器 UEditor配置:图片上传和文件上传独立使用方法

    使用UEditor编辑器自带的插件实现图片上传和文件上传功能,这里通过配置UEditor单独使用其内置的第三方插件swfupload来实现图片和文件的上传,通过对UEditor配置轻松实现图片批量上传 ...

  8. Kindeditor+web.py+SAE Storage 实现文件上传 - 开源中国社区

    Kindeditor+web.py+SAE Storage 实现文件上传 - 开源中国社区 Kindeditor+web.py+SAE Storage 实现文件上传

  9. 全网最详细的Eclipse里如何正确新建普通的Java web项目并发布到Tomcat上运行成功【博主强烈推荐】(图文详解)

    不多说,直接上干货! 首先,大家要明确,IDEA.Eclipse和MyEclipse等编辑器之间的新建和运行手法是不一样的. 如果是在Myeclipse里,则是File -> new -> ...

随机推荐

  1. Git使用方法

    一:Git是什么? Git是目前世界上最先进的分布式版本控制系统. 二:SVN与Git的最主要的区别? SVN是集中式版本控制系统,版本库是集中放在中央服务器的,而干活的时候,用的都是自己的电脑,所以 ...

  2. C#学校班级自动升级实现代码

    代码逻辑如下: //班级自动升级 //获取该学校还没有毕业的班级 List<ClassInfoes> classinfoeslist = classinfoesbll.GetList(Sc ...

  3. Orchard part8

    http://skywalkersoftwaredevelopment.net/blog/writing-an-orchard-webshop-module-from-scratch-part-8 定 ...

  4. Pandas将中文数据集转换为数值类别型数据集

    一个机器学习竞赛中,题目大意如下,本文主要记录数据处理过程,为了模型训练,第一步需要将中文数据集处理为数值类别数据集保存. 基于大数据的运营商投诉与故障关联分析 目标:原始数据集是含大量中文的xls格 ...

  5. iPad和iPhone开发区别

    原文:http://mobile.51cto.com/iphone-273895.htm iPad与iPhone 开发区别详解是本文要介绍的内容,先来看看他们的区别. 1.首先我们先从官方发布的SDK ...

  6. 使用 supervisor 管理进程

    安装: # yum install python-setuptools # easy_install supervisor 如果已经安装了epel和python-pip, 也可以简单 pip inst ...

  7. [课程设计]Scrum 2.2 多鱼点餐系统开发进度(下单页面修复&美化)

    [课程设计]Scrum 2.2 多鱼点餐系统开发进度  1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢志不渝,追求完美 4.团队选题:餐厅到店点餐系统WEB ...

  8. linux初始化配置-----网络配置

    一.设置linux网络 1)零时设置ip地址 由于centos7默认没有ifconfig命令所以为了使用方便我们先安装net-tool使我们能使用ifconfig命令查看ip地址 ·挂载系统光盘 [r ...

  9. Google 面试题和详解

    Google的面试题在刁钻古怪方面相当出名,甚至已经有些被神化的味道.这个话题已经探讨过很多次,而科技博客 BusinessInsider这两天先是贴出15道Google面试题并一一给出了答案,其中不 ...

  10. viewport 详解

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale= ...