SpringMVC transferTo初中数学路径问题题

spring mvc上传文件到指定的文件夹中,新手不会,_百度知道
spring mvc上传文件到指定的文件夹中,新手不会,
如何调用这个upload方法,传的参数是什么,求指教!@Controller@RequestMapping(value=&/manager&)publicclassUploadAction{@RequestMapping(value=&/upload&)publicStringupload(@Re...
如何调用这个upload方法,传的参数是什么,求指教!@Controller@RequestMapping(value = &/manager&)public class UploadAction { @RequestMapping(value = &/upload&) public String upload(@RequestParam(value = &file&, required = false) MultipartFile file,
HttpServletRequest request, ModelMap model) {
System.out.println(&开始&);
String path = DicInit.getRdaInstallPath();
String upversion = request.getParameter(&upversion&);
String fileName = file.getOriginalFilename()+&//upload//&+
System.out.println(path);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
return &result&; }}
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
来自电脑网络类芝麻团
采纳数:319
获赞数:723
参与团队:
第一个参数是你的前台传递进来的文件。第二个参数是request对象。第三个参数是spring mvc 绑定数据用的对象。根据你的代码 你的第三个参数可以不要。第一个参数 是前台form当中有个类似于&input type=&file& name=&file&/&的控件传递过来的文件。
这个资源会帮助你
1条折叠回答
为你推荐:
其他类似问题
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。(一)解决图片上传丢失
如果在Tomcat部署路径下创建upload文件夹,每次部署项目的时候upload文件夹会被自动删除再重新创建upload文件夹,因此保存在upload文件夹中的图片或其它文件都会被删除。要想保存的文件和图片不被自动删除解决办法如下:
在webapps并行的目录下,建一个upload文件,专门存储应用上传的文件。
其它磁盘路径也可以,在webapps并行的目录下创建建一个upload文件方便查看。
(二)如何使用img标签显示本地磁盘保存的图片
今天遇到这样一个问题,在eclipse使用默认浏览器可以打开img标签引用本地磁盘路径的图片,但是使用Chrome、360和Firefox等外部浏览器无法打开本地磁盘路径下的图片。解决方法如下:
在jsp页面标签引用本地路径下的图片,图片不会显示,需要在tomcat中配置虚拟路径。
在tomcat中配置虚拟路径步骤如下:
2.点击modules
真实路径:F:\Tomcat7\apache-tomcat-7.0.79
虚拟路径:/upload代替真实路径
创建images文件夹:项目自动在F:\Tomcat7\apache-tomcat-7.0.79下创建images文件夹
3.在jsp页面标签引用本地路径下的图片,使用虚拟路径引用本地磁盘下图片的方法如下:
方法:/虚拟路径/images文件夹/文件名
&img alt="" src="/upload/images/${newfilename}" width="140" height="170"/&
(三)文件上传实例演示
项目结构:
1./FileUpload/WebContent/FileUpload.jsp
&%@ page language="java" contentType="text/ charset=UTF-8"
pageEncoding="UTF-8"%&
&!DOCTYPE html&
http-equiv="Content-Type" content="text/ charset=UTF-8"&
&文件上传&
function check(){
var file=document.getElementById("file").
if(file.length==0||file==""){
alert("请选择上传文件");
return false;
return true;
action="${pageContext.request.contextPath }/fileUpload"
method="post" enctype="multipart/form-data" onsubmit="return check()"&
请选择文件: id="file" type="file" name="uploadfile"
multiple="multiple" /&/&/&
type="submit" value="上传" /&
2./FileUpload/src/com/wang/FileUploadController.java
package com.wang
import java.io.File
import java.util.ArrayList
import java.util.List
import java.util.UUID
import javax.servlet.http.HttpServletRequest
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.multipart.MultipartFile
@Controller
public class FileUploadController {
@RequestMapping("/fileUpload")
public String handleFormUpload(@RequestParam("uploadfile")List&MultipartFile& uploadfile, HttpServletRequest request) {
// 如果上传文件存在
if (!uploadfile.isEmpty() && uploadfile.size() & 0) {
// 遍历文件
for (MultipartFile file : uploadfile) {
// 获取上传文件的名称
String originalFilename = file.getOriginalFilename()
System.out.println("文件名"+originalFilename)
// 设置上传文件保存的地址目录
//String dirpath = request.getServletContext().getRealPath("/images")
//创建images文件夹
File filepath = new File("F:\\Tomcat7\\apache-tomcat-7.0.79\\images")
// 如果保存文件的目录不存在,创建upload文件夹
if (!filepath.exists()) {
filepath.mkdirs()
// 1.使用UUID重新命名上传文件的名称/2.替换上传文件的名称
String newFilename =UUID.randomUUID()+ originalFilename.replace(originalFilename, ".jpg")
System.out.println(newFilename)
// 使用MultipartFile的方法将文件上传到指定位置
file.transferTo(new File(filepath +File.separator+ newFilename))
System.out.println("目标路径"+filepath +File.separator+ newFilename)
//定义列表保存图片保存的路径
List&String& filenames=new ArrayList&String&()
filenames.add(newFilename)
request.setAttribute("filenames", filenames)
} catch (Exception e) {
e.printStackTrace()
return "error"
return "sucess"
3./FileUpload/WebContent/WEB-INF/jsp/sucess.jsp
&%@ page language="java" contentType="text/ charset=UTF-8"
pageEncoding="UTF-8"%&
&%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&
http-equiv="Content-Type" content="text/ charset=UTF-8"&
&文件上传页面&
&文件上传成功&
border="1"&
&图片展示&
items="${filenames}" var="newfilename"&
& alt="" src="/upload/images/${newfilename}" width="140" height="170"/& &
4.JSP页面显示虚拟路径下的图片:
5.JSP页面源码如图所示:
6.images文件夹保存图片永不丢失
SpringMVC从本地磁盘读取图片显示到JSP页面上
springmvc读取本地图片并显示
springMVC+img标签实现图片展示
如何使用页面中的img标签读取本地磁盘中的图片,并展现到页面上
img图片不存在时设置默认图片
没有更多推荐了,spring-servlet.xml
1    &!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --&
&bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"&
&property name="defaultEncoding" value="UTF-8" /&
&!-- 指定所上传文件的总大小,单位字节。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --&
&property name="maxUploadSize" value="" /&
&upload/index.jsp
1 &%@ page language="java" contentType="text/ charset=UTF-8" pageEncoding="UTF-8"%&
2 &!DOCTYPE HTML&
5 &meta http-equiv="Content-Type" content="text/ charset=UTF-8"&
6 &title&单图片上传&/title&
9 &fieldset&
10 &legend&图片上传&/legend&
11 &h2&只能上传单张10M以下的 PNG、JPG、GIF 格式的图片&/h2&
12 &form action="/shop/auth/photoUpload" method="post" enctype="multipart/form-data"&
选择文件:&input type="file" name="file"&
&input type="submit" value="上传"&
15 &/form&
16 &/fieldset&
17 &/body&
18 &/html&
或者使用ExtJs
js/user/photoUpload.js
1 Ext.onReady(function(){
Ext.create('Ext.form.Panel', {
title: '图片上传',
width: 600,
bodyPadding: 10,
frame: true,
renderTo: Ext.getBody(),
xtype: 'filefield',
name: 'file',
fieldLabel: 'Photo',
labelWidth: 50,
msgTarget: 'side',
fileUpload: true ,
allowBlank: false,
blankText:"Select an image",
emptyText: 'You can only upload a single PNG 10M or less, JPG, GIF format images',
anchor: '100%',
buttonText: '选择图片'
buttons: [{
text: '上传',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
url: '/shop/auth/photoUpload',
waitMsg: '正在上传图片...',
success: function(fp, o) {
Ext.Msg.alert('提示', o.result.msg);
pages/user/photoUpload.html
1 &!DOCTYPE html&
4 &meta charset="UTF-8"&
5 &title&图片上传&/title&
7 &link href="../../ext-4.2.1.883/resources/css/ext-all.css" rel="stylesheet"
type="text/css" /&
9 &script type="text/javascript" src="../../ext-4.2.1.883/ext-all.js"&&/script&
10 &script src="../../js/user/photoUpload.js" type="text/javascript"&&/script&
13 &/body&
14 &/html&  
AuthController.java
* 图片文件上传
@ResponseBody
@RequestMapping(value = "/photoUpload",method = RequestMethod.POST)
public ResultData&Object& photoUpload(MultipartFile file,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IllegalStateException, IOException{
ResultData&Object& resultData=new ResultData&&();
// 判断用户是否登录
/*User user=(User) session.getAttribute("user");
if (user==null) {
resultData.setCode(40029);
resultData.setMsg("用户未登录");
return resultD
if (file!=null) {// 判断上传的文件是否为空
String path=null;// 文件路径
String type=null;// 文件类型
String fileName=file.getOriginalFilename();// 文件原名称
System.out.println("上传的文件原名称:"+fileName);
// 判断文件类型
type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
if (type!=null) {// 判断文件类型是否为空
if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
String realPath=request.getSession().getServletContext().getRealPath("/");
// 自定义的文件名称
String trueFileName=String.valueOf(System.currentTimeMillis())+fileN
// 设置存放图片文件的路径
path=realPath+/*System.getProperty("file.separator")+*/trueFileN
System.out.println("存放图片文件的路径:"+path);
// 转存文件到指定的路径
file.transferTo(new File(path));
System.out.println("文件成功上传到指定目录下");
System.out.println("不是我们想要的文件类型,请按要求重新上传");
return null;
System.out.println("文件类型为空");
return null;
System.out.println("没有找到相对应的文件");
return null;
return resultD
&ResultData.java 代码如下:public class ResultData&T& {
private int code =200;
private Boolean success = public Boolean getSuccess() {
} public void setSuccess(Boolean success) {
this.success = } public T getData() {
} public void setData(T data) {
this.data = } public int getCode() {
} public void setCode(int code) {
if(200 != code){
this.code = } public String getMsg() {
} public void setMsg(String msg) {
this.msg = } }
阅读(...) 评论()https://meilishiyan-song.taobao.com/
https://meilishiyan-song.taobao.com/
package cn.com.mcd.import java.io.Fimport java.io.IOEimport java.io.Simport java.util.ArrayLimport java.util.HashMimport java.util.Limport java.util.Mimport java.util.UUID;
import javax.annotation.Rimport javax.servlet.http.HttpServletR
import org.apache.poi.xssf.usermodel.XSSFWimport org.slf4j.Limport org.slf4j.LoggerFimport org.springframework.stereotype.Cimport org.springframework.web.bind.annotation.RequestMimport org.springframework.web.bind.annotation.RequestMimport org.springframework.web.bind.annotation.RequestPimport org.springframework.web.bind.annotation.ResponseBimport org.springframework.web.multipart.MultipartF
import cn.com.mcd.common.ResultMimport cn.com.mcd.model.FileMimport cn.com.mcd.service.CustemerListSimport cn.com.mcd.util.UtilDateTimport cn.com.mcd.util.UtilExcelToTimport cn.com.mcd.util.constans.Cimport cn.com.mcd.util.constans.ConstantsEimport jxl.read.biff.BiffE/** * @author soya.song *
*/@Controller@RequestMapping("/custemerList")@SuppressWarnings("unused")public class CustemerListController implements Serializable{ private static final long serialVersionUID = 3695880L; private static final Logger log = LoggerFactory.getLogger(CustemerListController.class); @Resource private CustemerListService custemerListS static String prefix="customer_"; static String suffixTo=".txt";
* @param id
*/ @RequestMapping(value = "/uploadCustList",method = RequestMethod.POST) @ResponseBody public ResultModel uploadCustList(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException {
ResultModel resultModel=new ResultModel();
Map&String,Object& resultMap=new HashMap&String,Object&();
FileMain file=new FileMain();
log.info(this.getClass().getName()+".uploadCustList.start");
ResultModel result=new ResultModel();
String originalFilename="";//上传的文件的文件名
//校验上传文件上否为空
if(null==myfiles || myfiles.length&=0){
result.setResultMsg(Constants.SERVICE_ERROR_CODE);
result.setResultMsg(Constants.FILE_NULL_ERROR);
List&FileMain& resultList=new ArrayList&FileMain&();
for (MultipartFile myfile : myfiles) {
if (!myfile.isEmpty()) {
//获得文件后缀名
String suffix = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
//检查文件格式是否正确
if(!".lsx".equals(suffix) && !".xlsx".equals(suffix) ){
resultModel.setResultCode(ConstantsError.CHECK_EXCEL_NOT_EXIST_CODE);//cus1002
resultModel.setResultMsg(ConstantsError.CHECK_EXCEL_NOT_EXIST_MSG);//the file must be excel
return resultM
//获得文件源名
originalFilename=myfile.getOriginalFilename();
//转为File
String path=request.getSession().getServletContext().getRealPath("/file/upload/");//生成一个目录
String uuid=prefix+UtilDateTime.nowDateToString();//customer_YYYYMMDDHHMM
String fileName = uuid+ //文件全路径
String txtName = uuid+ suffixTo; //txt文件名(customer_YYYYMMDDHHMM.txt(时间为24小时制))
File f=new File(path,fileName);
//如果path路径不存在,创建一个文件夹
if(!f.exists()){
f.mkdirs();
myfile.transferTo(f);//没有这句话,生成的文件就是一个文件夹。有了以后,就会在path路径下,生成一个文件
//1.将文件信息保存到数据库
Map&String,Object& map=custemerListService.saveExcel(f);//
String flg=(String) map.get("flag") ;//
if(!"0".equals(flg)){//说明保存数据库没有成功//
if("1".equals(flg)){//说明校验失败//
result.setResultData(map);//
result.setResultCode(Constants.SERVICE_ERROR_CODE);//500//
result.setResultMsg(Constants.FILE_CHECK_ERROR);//导入文件数据有误//
log.info(this.getClass().getName()+".uploadCustList.文件上传保存到数据库校验失败result:"+result);//
//2.将excel文件转换为txt文件//
UtilExcelToTxt xt = UtilExcelToTxt.getInstance();//
resultMap=xt.excelToTxt(path+fileName, path,txtName);
//custemerListService
//将txt文件传入sftp
//如果导入成功一个文件,记录一次
file.setFlag("successful");//成功
//如果导入成功一个文件,记录一次
} catch (IllegalStateException | IOException e) {
file.setFlag("failure");//成功
log.error(this.getClass().getName()+".uploadCustList.end.上传excel文件controller报错",e);
// throw new DataBaseAccessException(5001+Constants.FILE_UPLOAD_ERROR+e);//excel文件导入失败
//如果导入成功一个文件,记录一次
file.setName(fileName);
file.setNum(i);
resultList.add(file);//对象装入list
result.setResultData(resultList);
阅读(...) 评论()
https://meilishiyan-song.taobao.com/在该示例中,阐述了SpringMVC如何上传文件。
1、上传页面upload.jsp
&form action="/TestSpringMVC3/data/uploadfile" enctype="multipart/form-data" method="post"&
file:&input type="file" name="file"&&br&
&input type="submit" value="upload file"&
&/body&2、controller配置文件&?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"&
使Spring支持自动检测组件,如注解的Controller
&context:component-scan base-package="cn.com.yy.controller"/&
&!-- 开启注解配置 --&
&mvc:annotation-driven/&
&!-- 支持JSP JSTL的解析器 --&
&bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&
&property name="prefix" value="/WEB-INF/page/"/&
&property name="suffix" value=".jsp"/&
&!-- 配置文件上传解析器 --&
&bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"&
&property name="defaultEncoding" value="utf-8"/&
&property name="maxUploadSize" value=""/&
&property name="maxInMemorySize" value="40960"/&
主要是添加了文件上传的解析器,配置了默认编码,最大的上传大小以及缓存大小等参数。
3、Controller
package cn.com.yy.
import java.io.F
import java.io.FileNotFoundE
import java.io.FileOutputS
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import org.springframework.stereotype.C
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestP
import org.springframework.web.multipart.commons.CommonsMultipartF
@Controller
@RequestMapping("/data")
public class FileUploadController {
* method1:通过参数CommonsMultipartFile进行解析
* @RequestParam("file")中的file对应于upload.jsp中的file类型的name对应的名称
* @param file
* @throws IOException
@RequestMapping(value="/uploadfile")
public String upload1(@RequestParam("file") CommonsMultipartFile file) throws IOException{
//获取文件名称
String fileName = file.getOriginalFilename();
//写入本地磁盘
InputStream is = file.getInputStream();
byte[] bs = new byte[1024];
OutputStream os = new FileOutputStream(new File("D:/temp/" + fileName));
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
os.close();
is.close();
return "upload_success";
@RequestMapping("/upload")
public String toPage(){
return "upload";
4、返回页面upload_success.jsp
upload file success!!
http://localhost:8080/TestSpringMVC3/data/upload
跳转到上传页面
选择文件上传
点击上传会跳转到上传成功页面。
上述方法只是简单的讲解了SpringMVC如何上传文件。
第二种方法:使用SpringMVC封装的方法进行文件上传
* 使用SpringMVC封装好的方法进行文件上传
* @param request
* @param response
* @throws IllegalStateException
* @throws IOException
@RequestMapping("/uploadfile2")
public void upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
//获取解析器
CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断是否是文件
if(resolver.isMultipart(request)){
//进行转换
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);
//获取所有文件名称
Iterator&String& it = multiRequest.getFileNames();
while(it.hasNext()){
//根据文件名称取文件
MultipartFile file = multiRequest.getFile(it.next());
String fileName = file.getOriginalFilename();
String localPath = "D:/temp/" + fileN
File newFile = new File(localPath);
//上传的文件写入到指定的文件中
file.transferTo(newFile);
该方法上传文件效率更优。
springMVC上传文件Java使用transferTo方法事半功倍
SpringMVC的 transferTo使用
transferto()方法,是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
springMVC的上传文件,spring的transferTo保存文件方法
SpringMVC上传图片总结(1)---常规方法进行图片上传,使用了MultipartFile、MultipartHttpServletRequest
上传文件或图片 controller层
没有更多推荐了,}

我要回帖

更多关于 php路径问题 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信