java中上传图片代码 java中上传图片代码是什么

java web开发,上传图片并读取

java web开发中,使用文件操作类来上传图片并读取,如下代码:

创新互联建站是一家集网站建设,黄平企业网站建设,黄平品牌网站建设,网站定制,黄平网站建设报价,网络营销,网络优化,黄平网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

* @desc: 图片处理工具

* @author: bingye

* @createTime: 2015-3-17 下午04:25:32

* @version: v1.0

*/

public class ImageUtil {

/**

* 将图片写到客户端

* @author: bingye

* @createTime: 2015-3-17 下午04:36:04

* @history:

* @param image

* @param response void

*/

public static void writeImage(byte[] image,HttpServletResponse response){

if(image==null){

return;

}

byte[] buffer=new byte[1024];

InputStream is=null;

OutputStream os=null;

try {

is=new ByteArrayInputStream(image);

os=response.getOutputStream();

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

os.write(buffer);

os.flush();

}

} catch (IOException e) {

e.printStackTrace();

} finally{

try {

if(is!=null){is.close();}

if(os!=null){os.close();}

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 获取指定路劲图片

* @author: bingye

* @createTime: 2015-3-21 上午10:50:44

* @param filePath

* @param response void

*/

public static void writeImage(String filePath,HttpServletResponse response){

File imageFile=new File(filePath); 

if(imageFile!=null  imageFile.exists()){

byte[] buffer=new byte[1024];

InputStream is=null;

OutputStream os=null;

try {

is=new FileInputStream(imageFile);

os=response.getOutputStream();

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

os.write(buffer);

os.flush();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally{

try {

if(is!=null){is.close();}

if(os!=null){os.close();}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/**

* 图片上传到文件夹

* @author: bingye

* @createTime: 2015-3-20 下午08:07:25

* @param file

* @param savePath

* @return boolean

*/

public static ResultDto uploadToLocal(CommonsMultipartFile file,String savePath){

if(file!=null  !file.isEmpty()){

//获取文件名称

String fileName=file.getOriginalFilename();

//获取后缀名

String suffixName=fileName.substring(fileName.indexOf(".")+1);

//新名称

String newFileName=System.currentTimeMillis()+"."+suffixName;

//新文件路劲

String filePath=savePath+newFileName;

//获取存储文件路径

File fileDir=new File(savePath);

if(!fileDir.exists()){

//如果文件夹没有:新建

fileDir.mkdirs();

}

FileOutputStream fos=null;

try {

fos=new FileOutputStream(filePath);

fos.write(file.getBytes());

fos.flush();

return ResultUtil.success("UPLOAD_SUCCESS", URLEncoder.encode(newFileName,"utf-8"));

} catch (Exception e) {

e.printStackTrace();

return ResultUtil.fail("UPLOAD_ERROR");

} finally{

try {

if(fos!=null){

fos.close();

}

} catch (IOException e) {

e.printStackTrace();

return ResultUtil.fail("UPLOAD_ERROR");

}

}

}

return ResultUtil.fail("UPLOAD_ERROR");

}

}

解释一下这段JAVA 关于图片上传的代码

private File file;

private String fileFileName;

private String picture;

//都有getter 和 setter

InputStream is = new FileInputStream(file);

//引入一个IO流的输入流

String root = ServletActionContext.getRequest()

.getRealPath("/bookpicture");

//通过REQUEST来得到相对地址,并在后面加上/bookpicture

File f = new File(root, this.getFileFileName());

//定义一个FILE文件,第一个参数是文件的路径,第二个是文件的名字

picture="."+"\\"+"bookpicture"+"\\"+this.getFileFileName();

//为PICTURE字符串赋值,/地址/文件名

System.out.println

("======picture====="+picture);

//从控制台输出Picture

OutputStream os = new FileOutputStream(f);

//第一个文件的输出流

byte[] buffer = new byte[1024];

//定义一个bufer的字符串,长度为1024

int len = 0;

while ((len = is.read(buffer)) 0) {

//如果从制定文件中读取到的信息为结束就继续循环

os.write(buffer, 0, len);

//将文件读出的内容写入到指定的文件中

}

java 中如何向服务器上传图片

我们使用一些已有的组件帮助我们实现这种上传功能。

常用的上传组件:

Apache 的 Commons FileUpload

JavaZoom的UploadBean

jspSmartUpload

以下,以FileUpload为例讲解

1、在jsp端

form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"

要注意enctype="multipart/form-data"

然后只需要放置一个file控件,并执行submit操作即可

input name="file" type="file" size="20"

input type="submit" name="submit" value="提交"

2、web端

核心代码如下:

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

request.setCharacterEncoding("UTF-8");

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

try {

List items = upload.parseRequest(request);

Iterator itr = items.iterator();

while (itr.hasNext()) {

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

if (item.isFormField()) {

System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));

} else {

if (item.getName() != null !item.getName().equals("")) {

System.out.println("上传文件的大小:" + item.getSize());

System.out.println("上传文件的类型:" + item.getContentType());

System.out.println("上传文件的名称:" + item.getName());

File tempFile = new File(item.getName());

File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());

item.write(file);

request.setAttribute("upload.message", "上传文件成功!");

}else{

request.setAttribute("upload.message", "没有选择上传文件!");

}

}

}

}catch(FileUploadException e){

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

request.setAttribute("upload.message", "上传文件失败!");

}

request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);

}

java怎样上传图片(写个例子谢谢);

我有一段上传图片的代码,并且可以根据实际,按月或按天等,生成存放图片的文件夹

首先在JSP上放一个FILE的标签这些我都不说了,你也一定明白,我直接把处理过程给你发过去

我把其中存到数据库中的内容删除了,你改一下就能用

/**

*

* 上传图片

* @param servlet

* @param request

* @param response

* @return

* @throws Exception

*/

//这里我是同步上传的,你随意

public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {

SimpleDate()Format formatDate() = new SimpleDate()Format("yyyyMM");

Date nowtime=new Date();

String formatnowtime=formatDate.format(nowtime);

File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //应保证在根目录中有此目录的存在 如果没有,下面则上创建新的文件夹

if(!root.isDirectory())

{

System.out.println("创建新文件夹成功"+formatnowtime);

root.mkdir();

}

int returnflag = 0;

SmartUpload mySmartUpload =new SmartUpload();

int file_size_max=1024000;

String ext="";

String url="uploadfile/images/"+formatnowtime+"/";

// 只允许上载此类文件

try{

// 初始化

mySmartUpload.initialize(servlet.getServletConfig(),request,response);

mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");

// 上载文件

mySmartUpload.upload();

} catch (Exception e){

response.sendRedirect()//返回页面

}

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);

if (myFile.isMissing()){ //没有选择图片做提示!

returnflag = 3;

}else{

String myFileName=myFile.getFileName(); //取得上载的文件的文件名

ext= myFile.getFileExt(); //取得后缀名

if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上传!)

int file_size=myFile.getSize(); //取得文件的大小

String saveurl="";

if(file_sizefile_size_max){

try{

//我上面说到,把操作数据库的代友删除了,这里就应该是判断,你的图片是不是已经存在了,存在要怎么处理,不存在要怎么处了,就是你的事了 }

//更改文件名,取得当前上传时间的毫秒数值

Calendar calendar = Calendar.getInstance();

//String filename = String.valueOf(calendar.getTimeInMillis());

String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");

String filename = did;

String flag = "0";

String path = request.getRealPath("/")+url;

String ename = myFile.getFileExt();

//.toLowerCase()转换大小写

saveurl=request.getRealPath("/")+url;

saveurl+=filename+"."+ext; //保存路径

myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);

//将图片信息插入到数据库中

// ------上传完成,开始生成缩略图-----

java.io.File file = new java.io.File(saveurl); //读入刚才上传的文件

String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的缩略图保存地址

Image src = javax.imageio.ImageIO.read(file); //构造Image对象

float tagsize=200;

int old_w=src.getWidth(null);

int old_h=src.getHeight(null);

int new_w=0;

int new_h=0;

int tempsize;

float tempdouble;

if(old_wold_h){

tempdouble=old_w/tagsize;

}else{

tempdouble=old_h/tagsize;

}

// new_w=Math.round(old_w/tempdouble);

// new_h=Math.round(old_h/tempdouble);//计算新图长宽

new_w=150;

new_h=110;//计算新图长宽

BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图

FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);

encoder.encode(tag); //近JPEG编码

newimage.close();

returnflag = 1;

}else{

returnflag = 0;

System.out.println("('上传文件大小不能超过"+(file_size_max/1000)+"K');");

}

}else{

returnflag = 2;

}

}

response.sendRedirect();

return "11";

}

网站名称:java中上传图片代码 java中上传图片代码是什么
当前路径:https://www.cdcxhl.com/article6/ddsgsog.html

成都网站建设公司_创新互联,为您提供品牌网站建设企业网站制作App设计自适应网站网站设计小程序开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设