热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

java上传图片cxf,servlet,spring标准方式

1.标准的java上传方式packagecom.weds.common.pay.servlet;importjava.io.File;importjava.io.IOException;imp

1.标准的java上传方式

 

package com.weds.common.pay.servlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

import com.weds.framework.core.common.model.JsonResult;

public class UploadServlet extends HttpServlet {

/**
* Destruction of the servlet.

*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet.

*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//实现上传的类
DiskFileItemFactory factory = new DiskFileItemFactory();//磁盘对象

ServletFileUpload upload = new ServletFileUpload(factory);//声明解析request对象
upload.setFileSizeMax(2*1024*1024);//设置每个文件最大为2M
upload.setSizeMax(4*1024*1024);//设置一共最多上传4M

try {
List list = upload.parseRequest(request);//解析
for(FileItem item:list){//判断FileItem类对象封装的数据是一个普通文本表单字段,还是一个文件表单字段,如果是普通表单字段则返回true,否则返回false。
if(!item.isFormField()){
//获取文件名
String fileName = item.getName();
//获取服务器端路径
String file_upload_loader =this.getServletContext().getRealPath("");
System.out.println("上传文件存放路径:"+file_upload_loader);
//将FileItem对象中保存的主体内容保存到某个指定的文件中。
item.write(new File(file_upload_loader+File.separator+fileName));
}else{
if(item.getFieldName().equalsIgnoreCase("username")){
String username = item.getString("utf-8");//将FileItem对象中保存的数据流内容以一个字符串返回
System.out.println(username);
}
if(item.getFieldName().equalsIgnoreCase("password")){
String password = item.getString("utf-8");
System.out.println(password);
}
}
}
//返回响应码(ResultCode)和响应值(ResultMsg)简单的JSON解析
JsonResult jsOnResult=new JsonResult();
JSONObject json = new JSONObject();
JSONObject jsOnObject= new JSONObject();
json.put("ResultCode",jsonResult.getCode());
json.put("ResultMsg",jsonResult.getMsg());
jsonObject.put("upload",json);
//System.out.println(jsonObject.toString());
out.print(jsonObject.toString());

} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
}
}

/**
* The doPost method of the servlet.

*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request,response);
}

/**
* Initialization of the servlet.

*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

然后配置servlet

   
upload
com.weds.common.pay.servlet.UploadServlet
3


upload
/upload

2. 标准java 通过 request的方式 笔者用的是spring + Apache cxf rest

 

 

接口定义
@POST  
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)//当前方法接收的参数类型
public String uploadFile();
接收实现
@Override
public String uploadFile() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
// 实现上传的类
DiskFileItemFactory factory = new DiskFileItemFactory();// 磁盘对象
ServletFileUpload upload = new ServletFileUpload(factory);// 声明解析request对象
upload.setFileSizeMax(2 * 1024 * 1024);// 设置每个文件最大为2M
upload.setSizeMax(4 * 1024 * 1024);// 设置一共最多上传4M
try {
List list = upload.parseRequest(request);// 解析
for (FileItem item : list) {// 判断FileItem类对象封装的数据是一个普通文本表单字段,还是一个文件表单字段,如果是普通表单字段则返回true,否则返回false。
if (!item.isFormField()) {
// 获取文件名
String fileName = item.getName();
// 获取服务器端路径
String file_upload_loader = request.getServletContext()
.getRealPath("");
System.out.println("上传文件存放路径:" + file_upload_loader);
// 将FileItem对象中保存的主体内容保存到某个指定的文件中。
item.write(new File(file_upload_loader + File.separator
+ fileName));
} else {
if (item.getFieldName().equalsIgnoreCase("username")) {
String username = item.getString("utf-8");// 将FileItem对象中保存的数据流内容以一个字符串返回
System.out.println(username);
}
if (item.getFieldName().equalsIgnoreCase("password")) {
String password = item.getString("utf-8");
System.out.println(password);
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// out.close();
}
return "ok";
}
注意这里获取request的时候,必须用上面的写法,通过 @Autowired注入获取request的方式在这里是不能用的,原因不详,求大神指点。

3.cxf rest 风格上传实现 @Multipart的 type是可以省略的,下面的写法,尤其是image,其实限制了图片的类型,要求很严格。

 

 

/** 
* 表单提交,文件上传
* @return
*/
@POST
@Path("/uploadimage")
@Consumes("multipart/form-data")
public String uploadFileByForm(
@Multipart(value="id",type="text/plain")String id,
@Multipart(value="name",type="text/plain")String name,
@Multipart(value="file",type="image/png")Attachment image);

接口的实现:

 

实现方式很多种:

如下是第一种,这是最简单的方式,直接取出流,然后读取

 

@Override
public String uploadFileByForm(
@Multipart(value = "id", type = "text/plain") String id,
@Multipart(value = "name", type = "text/plain") String name,
@Multipart(value = "file", type = "image/png") Attachment image) {
try {
OutputStream out = new FileOutputStream(new File("d:\\a.png"));
image.getDataHandler().writeTo(out);
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "ok";
}

第二种:

 

 

@Override
public String uploadFileByForm(
@Multipart(value = "id", type = "text/plain") String id,
@Multipart(value = "name", type = "text/plain") String name,
@Multipart(value = "file", type = "image/png") Attachment image) {
System.out.println("id:" + id);
System.out.println("name:" + name);
DataHandler dh = image.getDataHandler();
try {
InputStream ins = dh.getInputStream();
writeToFile(ins,"d:\\"+ new String(dh.getName().getBytes("iso-8859-1"),"utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
return "ok";
}

private void writeToFile(InputStream ins, String path) {
try {
OutputStream out = new FileOutputStream(new File(path));
byte[] bytes = new byte[1024];
while (ins.read(bytes) != -1) {
out.write(bytes);
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
当然 writeToFile方法也可以这么实现:
private void writeToFile(InputStream ins, String path) {
try {
OutputStream out = new FileOutputStream(new File(path));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = ins.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


注意:笔者在用cxf rest做上传的时候还遇到了个问题,折腾了半天:

 

笔者写了个cxf的Interceptor 拦截器,实现了AbstractPhaseInterceptor,用来拦截客户端传过来的数据,做数据处理,比如加解密,身份认证,等等,但是笔者有把客户端传过来的流出来分析了之后,在回写进去的操作,这么一来就发生了一个问题,这里处理的应该是字符流,而上传图片的时候是文件流,流只能读取一次,笔者处理完了之后,cxf的接收实现类里,在执行上面的读取文件流的图片的时候,就出现了个问题,笔者原本的图片是122k,由于拦截器的原因,这时候把图片写到文件里变成了200k,然后图片就打不开了,要注意!!!

另外:writeToFile(ins,"d:\\"+ new String(dh.getName().getBytes("iso-8859-1"),"utf-8"));,这里,红色部分是为了防止客户端上传的图片中文名字乱码,其实没啥鸟用,因为我们的文件流上传之后,一般会用GUID 代替原来的文件名字。

4.服务端 rest接口,直接接收客户端的流

 

/** 
* 表单提交,文件上传
* @return
*/
@POST
@Path("/uploadimage")
@Consumes("application/binary")
public String uploadFileByForm(InputStream inputStream);



 


推荐阅读
  • 基于Socket的多个客户端之间的聊天功能实现方法
    本文介绍了基于Socket的多个客户端之间实现聊天功能的方法,包括服务器端的实现和客户端的实现。服务器端通过每个用户的输出流向特定用户发送消息,而客户端通过输入流接收消息。同时,还介绍了相关的实体类和Socket的基本概念。 ... [详细]
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 在重复造轮子的情况下用ProxyServlet反向代理来减少工作量
    像不少公司内部不同团队都会自己研发自己工具产品,当各个产品逐渐成熟,到达了一定的发展瓶颈,同时每个产品都有着自己的入口,用户 ... [详细]
  • 如何在服务器主机上实现文件共享的方法和工具
    本文介绍了在服务器主机上实现文件共享的方法和工具,包括Linux主机和Windows主机的文件传输方式,Web运维和FTP/SFTP客户端运维两种方式,以及使用WinSCP工具将文件上传至Linux云服务器的操作方法。此外,还介绍了在迁移过程中需要安装迁移Agent并输入目的端服务器所在华为云的AK/SK,以及主机迁移服务会收集的源端服务器信息。 ... [详细]
  • 本文介绍了在Linux下安装和配置Kafka的方法,包括安装JDK、下载和解压Kafka、配置Kafka的参数,以及配置Kafka的日志目录、服务器IP和日志存放路径等。同时还提供了单机配置部署的方法和zookeeper地址和端口的配置。通过实操成功的案例,帮助读者快速完成Kafka的安装和配置。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 一句话解决高并发的核心原则
    本文介绍了解决高并发的核心原则,即将用户访问请求尽量往前推,避免访问CDN、静态服务器、动态服务器、数据库和存储,从而实现高性能、高并发、高可扩展的网站架构。同时提到了Google的成功案例,以及适用于千万级别PV站和亿级PV网站的架构层次。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 背景应用安全领域,各类攻击长久以来都危害着互联网上的应用,在web应用安全风险中,各类注入、跨站等攻击仍然占据着较前的位置。WAF(Web应用防火墙)正是为防御和阻断这类攻击而存在 ... [详细]
  • 目录浏览漏洞与目录遍历漏洞的危害及修复方法
    本文讨论了目录浏览漏洞与目录遍历漏洞的危害,包括网站结构暴露、隐秘文件访问等。同时介绍了检测方法,如使用漏洞扫描器和搜索关键词。最后提供了针对常见中间件的修复方式,包括关闭目录浏览功能。对于保护网站安全具有一定的参考价值。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 2018深入java目标计划及学习内容
    本文介绍了作者在2018年的深入java目标计划,包括学习计划和工作中要用到的内容。作者计划学习的内容包括kafka、zookeeper、hbase、hdoop、spark、elasticsearch、solr、spring cloud、mysql、mybatis等。其中,作者对jvm的学习有一定了解,并计划通读《jvm》一书。此外,作者还提到了《HotSpot实战》和《高性能MySQL》等书籍。 ... [详细]
author-avatar
技术小菜鸟
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有