spring mvc 上传图片mvc 怎么将文件上传到linux服务器

Spring MVC 结合Ajax实现文件上传(使用ajaxfileupload.js)
更多Spring相关文章,猛戳这里---》&
SpringMVC实现文件上传,直接上代码:
后台代码:
@RequestMapping(value = "/uploadApk")
@ResponseBody
public Object uploadApk(
@RequestParam(value = "apkFile") MultipartFile apkFile,
HttpServletRequest request, HttpServletResponse response) {
Map&String,Object& resMap = new HashMap&String,Object&();
if (apkFile != null) {
//获取保存的路径,
String realPath = request.getSession().getServletContext()
.getRealPath("/upload/apk");
if (apkFile.isEmpty()) {
// 未选择文件
resMap.put("status", StatusConstants.STATUS_PARM_IS_EMPTY);
// 文件原名称
String originFileName = apkFile.getOriginalFilename();
//这里使用Apache的FileUtils方法来进行保存
FileUtils.copyInputStreamToFile(apkFile.getInputStream(),
new File(realPath, originFileName));
resMap.put("status",StatusConstants.STATUS_OK);
} catch (IOException e) {
System.out.println("文件上传失败");
resMap.put("status", StatusConstants.STATUS_EXECPTION);
e.printStackTrace();
return resM
Spring配置文件中需要添加如下内容:
&!-- SpringMVC上传文件时,需配置MultipartResolver处理器 --&
&bean id="multipartResolver" class="org.springframework.monsMultipartResolver"&
&!-- 指定所上传文件的总大小不能超过80M......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --&
&property name="maxUploadSize" value=""/&
&!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --&
&!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --&
&bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"&
&property name="exceptionMappings"&
&!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --&
&prop key="org.springframework.web.multipart.MaxUploadSizeExceededException"&error_fileupload&/prop&
&/property&
jsp页面内容(这里结合的EasyUi的一些内容):
function ajaxFileUpload(){
//获取软件更新详情
var apkIntroduce = $("#apkInfo").val();
//开始上传文件时显示一个图片,文件上传完成将图片隐藏
//$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});
//执行上传文件操作的函数,使用encodeURI方法,防止传输中文字符的时候出现乱码
var uploadUrl = encodeURI(encodeURI(basePath + "uploadApk.do?apkIntroduce="+apkIntroduce));
$.ajaxFileUpload({
//处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
url:uploadUrl,
url:basePath + "uploadApk.do?apkIntroduce="+apkIntroduce,
secureuri:false,
//是否启用安全提交,默认为false
fileElementId:'apkFile',
//文件选择框的id属性
dataType:'text',
//服务器返回的格式,可以是json或xml等
success:function(data, status){
//服务器响应成功时的处理函数
data = data.replace("&PRE&", '');
//ajaxFileUpload会对服务器响应回来的text内容加上&pre&text&/pre&前后缀
data = data.replace("&/PRE&", '');
data = data.replace("&pre&", '');
data = data.replace("&/pre&", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
//将String字符串转换成json
var dataset = $.parseJSON(data);
if(dataset.status == "ok"){
$('#result').html("Apk上传成功&br/&");
$.messager.alert("提示","上传成功");
//关闭添加窗口
addApkWindow.window('close');
//刷新页面
datagrid.datagrid('reload');
}else if ( dataset.status == "parm_is_empty"){
$('#result').html("没有选择APK!");
$('#result').html('Apk上传失败,请重试!!');
error:function(data, status, e){ //服务器响应失败时的处理函数
console.log(e);
console.log(data);
$('#result').html('APK上传失败,请重试!!');
Html页面代码:
&div id="addApkWindows"&
&!-- http://www./lib/view/open3.html --&
&div id="result"&&/div&
&img id="uploadImage" src=".cn/favicon.ico"& --&
软件更新详情:&br/&
&textarea rows="2" cols="30" id="apkInfo"&&/textarea&
&br/&上传文件:&br/&
&input type="file" id="apkFile" name="apkFile"/&&br/&
&input type="button" value="上传" onclick="ajaxFileUpload()"/&
上面的JSP代码中,使用到了JS中的encodeURI方法,这个的目的是为了防止在传递中文参数时的乱码问题,当然,如果只传文件的话,则没有必要使用encodeURI
参考网址:
PS :更新于
感谢『XL鹰』的补充--》
dataType:'text', //服务器返回的格式,可以是json或xml等
这里改成了text不要用json,会有问题,这里改成text后,下面的date就不需要转换了
这里有一条评论讲的很好
sea_wind 为他的用户名,树袋熊的图标的用户讲的
版权所有:《》 => 《》
本文地址:
除非注明,文章均为 《》 原创,欢迎转载!转载请注明本文地址,谢谢。
58同城程序猿一枚,宅男系列
微信公众号:攀爬蜗牛(dutycode_com)
Powered by &&Themes by &&
&&&&11.89ms基于前面文章的基础上。
&&& 需要的jar
&&& &二、配置
&&1、& spmvc-servlet.xml
&?xml version="1.0" encoding="UTF-8" ?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"&
&!-- 默认的注解映射的支持 ,它会自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter--&
&mvc:annotation-driven /&
&!-- 自动扫描注解的Controller --&
&context:component-scan base-package="com.wy.controller" /&
&bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /&
&!-- 映射处理器 --&
&bean id="simpleUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&
&property name="mappings"&
&prop key="/fileUploadController.do"&fileUploadController&/prop&
&/property&
&!-- ParameterMethodNameResolver 解析请求参数,并将它匹配Controller中的方法名 --&
&bean id="parameterMethodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"&
&property name="paramName" value="action" /&
&bean id="fileUploadController"
class="com.wy.controller.FileUploadController"&
&property name="methodNameResolver"
ref="parameterMethodNameResolver"&
&/property&
&!-- 文件上传表单的视图解析器 --&
&bean id="multipartResolver"
class="org.springframework.monsMultipartResolver"&
&!-- one of the
the maximum file size in bytes --&
&property name="maxUploadSize" value="204800" /&
2、Controller
& 使用两种方式:
&&&&&& 一种是基于注解的,另一种传统的方式HttpServletRequest
&&&&& 使用第二种方式时要注意:操作方法中对应的方法参数前两位必须是request,response对象并且都要加上,否则会出现 No request handling method with name 'insert' in class& "ClassName",页面显示为404错误这个问题出现在使用多操作控制器情况下,相关的操作方法中对应的方法参数前两位必须是request,response对象,必须要有,否则会报如上异常。
package com.wy.
import java.util.L
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpS
import org.springframework.stereotype.C
import org.springframework.util.MultiValueM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestP
import org.springframework.web.multipart.MultipartF
import org.springframework.web.multipart.MultipartHttpServletR
import org.springframework.web.servlet.ModelAndV
import org.springframework.web.servlet.mvc.multiaction.MultiActionC
@Controller
@RequestMapping("/fileUploadController")
public class FileUploadController extends MultiActionController {
* 1、文件上传
* @param request
* @param response
public ModelAndView uploadFiles(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView();
// 转型为MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)
// 获得上传的文件(根据前台的name名称得到上传的文件)
MultiValueMap&String, MultipartFile& multiValueMap = multipartRequest.getMultiFileMap();
List&MultipartFile& file = multiValueMap.get("clientFile");
//MultipartFile file = multipartRequest.getFile("clientFile");
if(!file.isEmpty()){
//在这里就可以对file进行处理了,可以根据自己的需求把它存到数据库或者服务器的某个文件夹
System.out.println("================="+file.get(0).getName() + file.get(0).getSize());
* @param name
* @param file
* @param session
@RequestMapping(value="/uploadFile", method=RequestMethod.POST)
public String uploadFile(@RequestParam("fileName") String fileName,
@RequestParam("clientFile") MultipartFile clientFile, HttpSession session){
if (!clientFile.isEmpty()) {
//在这里就可以对file进行处理了,可以根据自己的需求把它存到数据库或者服务器的某个文件夹
System.out.println("================="+clientFile.getSize());
return "";
&对文件的具体实现
import java.io.F
import java.io.IOE
import java.util.I
import java.util.UUID;
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.web.multipart.MultipartF
import org.springframework.web.multipart.MultipartHttpServletR
import org.springframework.monsMultipartR
public class AddImage {
public String upload2(HttpServletRequest request,HttpServletResponse response, String fileName) throws IllegalStateException, IOException {
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)
//取得request中的所有文件名
Iterator&String& iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为&&,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
System.out.println(myFileName);
//重命名上传后的文件名
fileName = UUID.randomUUID() +"+"+ file.getOriginalFilename();
//定义上传路径
String path = "F:/workspace/myproject/WebRoot/image/" + fileN
File localFile = new File(path);
file.transferTo(localFile);
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
return fileN
&& upload.jsp
&%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
&!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&
&title&file upload test&/title&
&form method="post" action="&%=path %&/fileUploadController/uploadFile" enctype="multipart/form-data"&
文件名: &input type="text" name="fileName" /&&br/&
&input type="file" name="clientFile" /&&br/&
&input type="submit" value="上传文件 "/&
springmvc文件上传2中方法
1、spring框架下载http://maven.springframework.org/release/org/springframework/spring/2、apache系列软件下载http
1,Spring的主要子项目:-1,SpringFramework(Core):Spring项目的核心。提供IoC,AOP,MVC等核心功能。-2,SpringWebFlow:工作流引擎。-3
SpringScala项目的目的是为了简化在Scala应用中使用Spring框架。我们相信很多Spring用户想尝试Scala,但并不像放弃他们在Spring框架上的积累,这个项目就是为这些人准备
pgGallery是一个采用Spring框架和数据库开发的Web相册。项目主页:
common-orm是ORM框架,兼容spring事务,提供分库分表功能。项目主页:
博客分类:在做java开发时,如果用到spring,那么在做j2ee开发都可能用到spring的配置文件,那么spring的配置文件名到底应是什么呢?默认的情况下spring会从web-inf目录下
)进行查找.举个简单的例子,在我的web.xml中是这么定义的:classpath*:META-INF/spring/application-context.xml那么在META-INF/spring这个
Spring是什么:Spring是一个轻量级的DI和AOP容器框架。说它轻量级有一大部分原因是相对与EJB的(虽然本人从没有接触过EJB的应用),重要的是,Spring是非侵入式的,基于spring
正则表达式在线测试工具
FaceYe @ 2015 &&&&
ICP备案号:粤ICP备1500070上传文件到服务器的Linux命令 - 博客频道 - CSDN.NET
有志者,事可成
——贵在坚持
分类:linux
对拷文件夹 (包括文件夹本身)
scp -r & /home/wwwroot/www/charts/util root@192.168.1.65:/home/wwwroot/limesurvey_back/scp
对拷文件夹下所有文件 (不包括文件夹本身)
scp&& /home/wwwroot/www/charts/util/* root@192.168.1.65:/home/wwwroot/limesurvey_back/scp
&对拷文件并重命名
scp&& /home/wwwroot/www/charts/util/a.txt root@192.168.1.65:/home/wwwroot/limesurvey_back/scp/b.text
Linux下scp的用法
scp就是secure copy,一个在linux下用来进行远程拷贝文件的命令。
有时我们需要获得远程服务器上的某个文件,该服务器既没有配置ftp服务器,也没有做共享,无法通过常规途径获得文件时,只需要通过简单的scp命令便可达到目的。
一、将本机文件复制到远程服务器上
#scp /home/administrator/news.txt root@192.168.6.129:/etc/squid
/home/administrator/&&&&& 本地文件的绝对路径
news.txt&&&&&&&&&&&&&&&&&&&&&&& & 要复制到服务器上的本地文件
root&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& 通过root用户登录到远程服务器(也可以使用其他拥有同等权限的用户)
192.168.6.129&&&&&&&&&&&&&&& 远程服务器的ip地址(也可以使用域名或机器名)
/etc/squid&& &&&&&&&&&&&&&&&& && 将本地文件复制到位于远程服务器上的路径
如图通过root用户登录远程服务器,输入yes表示同意建立ssh连接
按提示输入root用户的密码
如图所示建立连接后开始传输文件,显示百分比、实际时间和传送速度等信息
二、将远程服务器上的文件复制到本机
#scp remote@:/usr/local/sin.sh /home/administrator
remote&&&&&&&&&&&&&&&& & & & 通过remote用户登录到远程服务器(也可以使用其他拥有同等权限的用户)
&&&&&&&&& & & 远程服务器的域名(当然也可以使用该服务器ip地址)
/usr/local/sin.sh&& & & & & 欲复制到本机的位于远程服务器上的文件
/home/administrator& 将远程文件复制到本地的绝对路径
注意两点:
1.如果远程服务器防火墙有特殊限制,scp便要走特殊端口,具体用什么端口视情况而定,命令格式如下:
#scp -p 4588 remote@:/usr/local/sin.sh /home/administrator
2.使用scp要注意所使用的用户是否具有可读取远程服务器相应文件的权限。
在Cygwin中执行:$ ssh username@remotehost
命令scp基于SSH协议,可以将本地文件拷贝到远程服务上的指定目录,格式如下:
$ scp filename username@remotehost:remotedirectory
执行:$ scp ipmsg.log admin@10.25.1.202:/home/admin
3 ftp/sftp
首先用root用户登录远程Linux服务器,将admin用户添加到FTP账户中。
通过echo命令追加一行到user_list文件中:# echo admin && user_list
之后通过service命令开启FTP服务:# service vsftpd start
现在就可以在本机访问FTP远程服务器了,然后通过put命令上传文件了。
在Cygwin中执行:$ sftp admin@10.25.1.202
4 SSH Windows Client
SSH提供了一个scp2.exe作为Windows下的scp命令工具。
具体位置:C:\Program Files (x86)\SSH Communications Security\SSH Secure Shell
排名:第3955名
(27)(10)(6)(11)(56)(10)(22)(5)(7)(1)(7)(6)(8)(8)(6)(6)(8)(2)(7)(10)(2)(5)(5)(4)(5)(3)(15)使用SpringMVC的J2ee项目在windows下可以访问,linux下无法访问url path
[问题点数:30分,结帖人amos82]
使用SpringMVC的J2ee项目在windows下可以访问,linux下无法访问url path
[问题点数:30分,结帖人amos82]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
2016年1月 Java大版内专家分月排行榜第二2015年12月 Java大版内专家分月排行榜第二2015年8月 Java大版内专家分月排行榜第二2015年3月 Java大版内专家分月排行榜第二2015年1月 Java大版内专家分月排行榜第二2014年12月 Java大版内专家分月排行榜第二2014年11月 Java大版内专家分月排行榜第二2014年6月 Java大版内专家分月排行榜第二2014年4月 Java大版内专家分月排行榜第二2014年1月 Java大版内专家分月排行榜第二2013年11月 Java大版内专家分月排行榜第二
2015年9月 Java大版内专家分月排行榜第三2015年6月 Java大版内专家分月排行榜第三2015年5月 Java大版内专家分月排行榜第三2015年2月 Java大版内专家分月排行榜第三2014年3月 Java大版内专家分月排行榜第三2013年12月 Java大版内专家分月排行榜第三
本帖子已过去太久远了,不再提供回复功能。拥有必珍惜 的BLOG
用户名:拥有必珍惜
访问量:843
注册日期:
阅读量:5863
阅读量:12276
阅读量:334800
阅读量:1039544
51CTO推荐博文
package com....;
import java.io.F
import java.io.IOE
import java.text.SimpleDateF
import java.util.D
import java.util.HashM
import java.util.M
import javax.servlet.ServletE
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import mons.io.FileU
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.C
import org.springframework.util.FileCopyU
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.ResponseB
import org.springframework.web.multipart.MultipartF
import org.springframework.web.multipart.MultipartHttpServletR
* @describe 上传头像文件,上传文件夹需存在
@Controller
public class ThenHeadPortraitController
private final int MAX_SIZE = 1024 * 1024 * 1;
//限制用户头像的最大值为1M
private String[] extendNamesArray = {".jpg",".jpeg"};
//用户头像的扩展名数组,方面验证
private String rootP
//文件根路径
private String imageNewP
//头像新路径(包含头像名以及扩展名)
private String imageOldP
//头像在数据库中的原有路径(包含头像名以及扩展名)
private String imageN
//头像的新名字(时间+用户名),时间精确到毫秒
private String extendN
//头像的扩展名,进行扩展名验证,以达到对用户头像的图片类型限制
//用于返回上传头像的信息
private String imageURL;
//用于返回用户头像存放的物理路径
private MultipartFile imageF
//测试时使用方法
@RequestMapping(value="/then/uploadHeadPortrait.jspx",method= RequestMethod.GET)
public void
upload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
request.getRequestDispatcher("../MyJsp.jsp").forward(request,response);
@RequestMapping(value="/then/uploadHeadPortrait.jspx",method= RequestMethod.POST)
@ResponseBody
public Map&String,String& uploadHeadPortrait(String account,HttpServletRequest request){
String imageAccount =
//存储用户临时的用户名,以便进行文件的命名
Map&String,String& map = new HashMap&String,String&();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)
//获取上传头像
imageFile = multipartRequest.getFile("file");
//获取上传头像的文件名
String fileName = imageFile.getOriginalFilename();
System.out.println("OriginalFilename:"+fileName);
//获取文件扩展名
extendName = fileName.substring(fileName.lastIndexOf("."));
//获取上传头像的大小
int imageSize = (int) imageFile.getSize();
//验证头像的扩展名是否符合要求
if((extendName.equals(extendNamesArray[0])||extendName.equals(extendNamesArray[1]))&&(imageSize&=MAX_SIZE)){
rootPath =
request.getSession().getServletContext().getRealPath("//upload");
System.out.println("rootPath:"+rootPath);
imageNames = getUploadCurrentTime() + imageA //重新命名上传头像名称
System.out.println("imageNames:"+imageNames);
imageNewPath = rootPath+"\\"+imageNames+extendN
System.out.println("imageNewPath:"+imageNewPath);
//判断新路径是否等于数据库中已存在的路径,不等于,则存储新路径,删除原有头像文件
if(!imageNewPath.equals(getDatabaseImageOldPath(imageAccount))){
if(getDatabaseImageOldPath(imageAccount)!=null&&getDatabaseImageOldPath(imageAccount)!=""){
File file = new File(getDatabaseImageOldPath(imageAccount));
if(imageSave(imageAccount,imageNewPath)){
if(file.exists()){
file.delete();
message = "头像上传成功";
imageURL = imageNewP
map.put("message",message);
map.put("imageURL",imageURL);
//保存失败
message = "头像保存失败";
imageURL =
map.put("message",message);
map.put("imageURL",imageURL);
message = "头像上传失败";
imageURL =
map.put("message",message);
map.put("imageURL",imageURL);
//图像格式不符合或者头像的大小大于1M
message = "头像上传失败,格式或大小不符合";
imageURL =
map.put("message",message);
map.put("imageURL",imageURL);
//获取头上上传的当前时间
private String getUploadCurrentTime(){
return new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date() );
//获取数据库中原有路径,如有则返回路径,否则返回可能为空或“”
private String getDatabaseImageOldPath(String account){
UserDetail userDetatilOldPath=userService.findByUsername(account).getDetail();
imageOldPath =
userDetatilOldPath.getAvatar();
return imageOldP
//对原有头像的新路径进行存储,存储后进行检查,时候已经存储,存储成功返回true,失败则返回false
private boolean imageSave(String account,String imageNewPath){
File uploadFile = new File(imageNewPath);
FileCopyUtils.copy(imageFile.getBytes(), uploadFile);
FileUtils.copyInputStreamToFile(imageFile.getInputStream(), new File(imageNewPath));
UserDetail ud=userService.findByUsername(account).getDetail();
ud.setAvatar(imageNewPath);
//设置头像新路径
userDetailService.update(ud) ;
//对头像进行数据库更新操作
if(getDatabaseImageOldPath(account)!=null||getDatabaseImageOldPath(account).equals("")){
} catch (IOException e) {
e.printStackTrace();
System.out.println("【上传头像失败...】");
@Autowired
private UserDetailService userDetailS
@Autowired
private UserService userS
}本文出自 “” 博客,请务必保留此出处
了这篇文章
类别:┆阅读(0)┆评论(0)

我要回帖

更多关于 spring mvc 上传图片 的文章

 

随机推荐