文件管理 · 2024年10月13日

spring标签文件上传|求SpringMVC大文件上传详解及实例代码

⑴ 如何用spring集成mongodb实现文件上传

首先要把必要的MongoDB需要的jar加进项目中定义mongoDB的bean[html] view plain <bean id="mongoClient" class="com.mongodb.MongoClient"><constructor-arg index="0" type="java.lang.String" name="host" value="127.0.0.1" /><constructor-arg index="1" type="int" name="port" value="27017" /></bean> 自定义实现mongodb增删改实体类[html] view plain <bean id="mongoDB" class="com.test.MongoDB"><property name="mongoClient" ref="mongoClient" /><property name="dbName" value="orcl" /></bean> 定义mongoClient基础类[java] view plain public class MongoDB {private MongoClient mongoClient;private String dbName;/*** 获取名为dbName数据库** @return*/public DB getDB() {return mongoClient.getDB(dbName);}public MongoClient getMongoClient() {return mongoClient;}public void setMongoClient(MongoClient mongoClient) {this.mongoClient = mongoClient;}public String getDbName() {return dbName;}public void setDbName(String dbName) {this.dbName = dbName;}} 定义mongodb操作Dao类[java] view plain /*** 增** @param bean* @return*/public T save(T bean) {String beanjson = JsonUtil.getJSONString(bean);DBCollection collection = mongoDB.getDB().getCollection(clazz.getSimpleName());collection.save((DBObject)JSON.parse(beanJson));return bean;}/*** 删* @param id*/public void remove(String id) {DBCollection collection = mongoDB.getDB().getCollection(clazz.getSimpleName());BasicDBObject doc = new BasicDBObject();doc.put("_id", id);collection.remove(doc);}/*** 改* @param query* @param newDoc*/public void update(BasicDBObject query, BasicDBObject newDoc) {DBCollection collection = mongoDB.getDB().getCollection(clazz.getSimpleName());collection.update(query, newDoc);} 定义保存文件类[java] view plain /*** 保存文件到MongoDB GridFS** @param in – 需要保存文件的输入流* @param id – 需要保存文件的唯一ID* @param fileName – 需要保存文件的文件名* @param contentType – 需要保存文件的文件类型* @param downloadName – 需要保存文件被下载时的文件名*/public void save(InputStream in, String id, String fileName, String contentType, String downloadName) {GridFS fs = new GridFS(mongoDB.getDB(), this.getClass().getSimpleName());GridFSInputFile fsFile = fs.createFile(in);fsFile.setId(id);fsFile.setFilename(fileName);fsFile.setContentType(contentType);fsFile.put("downloadName", downloadName);fsFile.save();}/*** 从MongoDB GridFS文件系统中删除指定ID的文件** @param id*/public void remove(String id) {GridFS fs = new GridFS(mongoDB.getDB(), this.getClass().getSimpleName());BasicDBObject query = new BasicDBObject("_id", id);fs.remove(query);}/*** 从MongoDB GridFS文件系统中批量删除指定ID的文件* @param ids*/public void batchRemove(String… ids) {GridFS fs = new GridFS(mongoDB.getDB(), this.getClass().getSimpleName());for(String id : ids){BasicDBObject query = new BasicDBObject("_id", id);fs.remove(query);}}

⑵ springboot多文件上传

MultipartFile提供了以下方法来获取上传文件的信息:getOriginalFilename,获取上传的文件名字; getBytes,获取上传文件内容,转为字节数组; getInputStream,获取一个InputStream; isEmpty,文件上传内容为空,或者根本就没有文件上传; getSize,文件上传的大小。 transferTo(File dest),保存文件到目标文件系统; 同时上传多个文件,则使用MultipartFile数组类来接受多个文件上传: //多文件上传 @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)     @ResponseBody    public String handleFileUpload(HttpServletRequest request){         List<MultipartFile> files = ((MultipartHttpServletRequest) request)                 .getFiles("file");         MultipartFile file = null;         BufferedOutputStream stream = null;         for (int i = 0; i < files.size(); ++i) {             file = files.get(i);             if (!file.isEmpty()) {                 try {                     byte[] bytes = file.getBytes();                     stream = new BufferedOutputStream(new FileOutputStream(                             new File(file.getOriginalFilename())));                     stream.write(bytes);                     stream.close();                 } catch (Exception e) {                     stream = null;                     return "You failed to upload " + i + " => "                            + e.getMessage();                 }             } else {                 return "You failed to upload " + i                         + " because the file was empty.";             }         }         return "upload successful";     } 可以通过配置application.properties对SpringBoot上传的文件进行限定默认为如下配置:spring.servlet.multipart.enabled=true spring.servlet.multipart.file-size-threshold=0 spring.servlet.multipart.location= spring.servlet.multipart.max-file-size=1MB spring.servlet.multipart.max-request-size=10MB spring.servlet.multipart.resolve-lazily=false enabled默认为true,既允许附件上传。 file-size-threshold限定了当上传文件超过一定长度时,就先写到临时文件里。有助于上传文件不占用过多的内存,单位是MB或KB,默认0,既不限定阈值。 location指的是临时文件的存放目录,如果不设定,则web服务器提供一个临时目录。 max-file-size属性指定了单个文件的最大长度,默认1MB,max-request-size属性说明单次HTTP请求上传的最大长度,默认10MB. resolve-lazily表示当文件和参数被访问的时候再被解析成文件。

⑶ 如何使用springmvc实现文件上传

在现在web应用的开发,springMvc使用频率是比较广泛的,现在给大家总结一下springMvc的上传附件的应用,希望对大家有帮助,废话不多说,看效果

准备jar包

4.准备上传代码@Controller//spring使用注解管理bean@RequestMapping("/upload")//向外暴露资源路径,访问到该类public class UploadController {/*** 上传功能* @return* @throws IOException*/@RequestMapping("/uploadFile")//向外暴露资源路径,访问到该方法public String uploadFile(MultipartFile imgFile,HttpServletRequest req) throws IOException{if(imgFile != null ){//获取文件输入流InputStream inputStream = imgFile.getInputStream();//随机产生文件名,原因是:避免上传的附件覆盖之前的附件String randName = UUID.randomUUID().toString();//随机文件名//获取文件原名String originalFilename = imgFile.getOriginalFilename();//获取文件后缀名(如:jpgpng…)String extension = FilenameUtils.getExtension(originalFilename);//新名字String newName = randName+"."+extension;//获取servletContextServletContext servletContext = req.getSession().getServletContext();//获取根路径String rootPath = servletContext.getRealPath("/");File file = new File(rootPath,"upload");//判断文件是否存在,若不存在,则创建它if(!file.exists()){file.mkdirs();}//获取最终输出的位置FileOutputStream fileOutputStream = new FileOutputStream(new File(file,newName));//上传附件IOUtils.(inputStream, fileOutputStream);}return null;}}

⑷ springcloud涓浣跨敤fegin鏂瑰紡涓婁紶鏂囦欢

鍦⊿pring Cloud涓浣跨敤Feign鏂瑰紡涓婁紶鏂囦欢锛屽彲浠ヤ娇鐢∕ultipartFile浣滀负璇锋眰浣撴潵鍙戦佹枃浠讹紝鍏蜂綋鎿嶄綔濡備笅锛

宸ュ叿/鍘熸枡锛氳仈鎯崇數鑴戝ぉ閫510S銆乄indows10銆丼un Java SE Development Kit锛圝DK锛17.0.1銆

1銆侀栧厛纭淇濆凡缁忔坊鍔犱簡Feign鐨勪緷璧栥傚湪Maven椤圭洰涓锛屽皢浠ヤ笅渚濊禆娣诲姞鍒皃om.xml鏂囦欢涓銆

Feign鐨勪紭鍔

绠鍖栧㈡埛绔浠g爜锛欶eign鐨勫0鏄庡紡缂栫▼鏂瑰紡鍙浠ュぇ澶х畝鍖栧㈡埛绔浠g爜鐨勭紪鍐欍傞氳繃娉ㄨВ鐨勬柟寮忥紝寮鍙戣呭彲浠ヨ交鏉惧湴瀹氫箟鍜屽0鏄庤锋眰锛岃屾棤闇鍏冲績搴曞眰HTTP璇锋眰鐨勭粏鑺傘

璐熻浇鍧囪锛欶eign鏁村悎浜哛ibbon锛屽叿鏈夎礋杞藉潎琛$殑鑳藉姏銆俁ibbon鏄涓涓浼樼鐨勮礋杞藉潎琛″櫒锛屽彲浠ユ牴鎹涓嶅悓鐨勭瓥鐣ヨ繘琛岃锋眰鍒嗗彂锛屾彁楂樼郴缁熺殑鍚炲悙閲忓拰鎬ц兘銆

鏈嶅姟闄嶇骇鍜岀啍鏂锛欶eign鏁村悎浜咹ystrix锛屽叿鏈夋湇鍔¢檷绾у拰鐔旀柇鐨勮兘鍔涖傚綋鏈嶅姟鎻愪緵鑰呭嚭鐜版晠闅滄垨鍝嶅簲杩囨參鏃讹紝Feign鍙浠ヨ嚜鍔ㄨЕ鍙戦檷绾ч昏緫锛屽噺灏戝瑰㈡埛绔鐨勫奖鍝嶃

⑸ spring mvc word文件上传之后可预览的实现方法或者步骤

你好!springmvc文件上传1.加入jar包:commons-fileupload-1.2.2.jarcommons-io-2.0.1.jarlperson.java中加属性,实现get ,set方法private String photoPath;2.创建WebRoot/upload目录,存放上传的文件1 <sf:form id="p" action="saveOrUpdate" 2 method="post" 3 modelAttribute="person" 4 enctype="multipart/form-data">5 6 <sf:hidden path="id"/> 7 name: <sf:input path="name"/><br>8 age: <sf:input path="age"/><br>9 photo: <input type="file" name="photo"/><br>上面第9行文件上传框,不能和实体对象属性同名,类型不同controller配置1 12、文件上传功能实现 配置文件上传解析器2 @RequestMapping(value={"/saveOrUpdate"},method=RequestMethod.POST)3 public String saveOrUpdate(Person p,4 @RequestParam("photo") MultipartFile file,5 HttpServletRequest request6 ) throws IOException{7 if(!file.isEmpty()){8 ServletContext sc = request.getSession().getServletContext();9 String dir = sc.getRealPath(“/upload”); //设定文件保存的目录10 11 String filename = file.getOriginalFilename(); //得到上传时的文件名12 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());13 14 p.setPhotoPath(“/upload/”+filename); //设置图片所在路径15 16 System.out.println("upload over. "+ filename);17 } 18 ps.saveOrUpdate(p); 19 return "redirect:/person/list.action"; //重定向20 }3.文件上传功能实现 spring-mvc.xml 配置文件上传解析器1 <!– 文件上传解析器 id 必须为multipartResolver –>2 <bean id="multipartResolver" 3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">4 <property name="maxUploadSize" value=“10485760"/> 5 </bean>6 7 maxUploadSize以字节为单位:10485760 =10M id名称必须这样写1 映射资源目录2 <mvc:resources location="/upload/" mapping="/upload/**"/>随即文件名常用的三种方式:文件上传功能(增强:防止文件重名覆盖)fileName = UUID.randomUUID().toString() + extName;fileName = System.nanoTime() + extName;fileName = System.currentTimeMillis() + extName;1 if(!file.isEmpty()){2 ServletContext sc = request.getSession().getServletContext();3 String dir = sc.getRealPath("/upload");4 String filename = file.getOriginalFilename();5 6 7 long _lTime = System.nanoTime();8 String _ext = filename.substring(filename.lastIndexOf("."));9 filename = _lTime + _ext;10 11 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());12 13 p.setPhotoPath("/upload/"+filename);14 15 System.out.println("upload over. "+ filename);16 }图片显示 personList.jsp1 <td><img src="${pageContext.request.contextPath}${p.photoPath}">${p.photoPath}</td>

⑹ java spring mvc 客户端上传文件到服务器端

Web文件上传采用POST的方式,与POST提交表单不同的是,上传文件需要设置FORM的enctype属性为multipart/form-data.由于上传的文件会比较大,因此需要设置该参数指定浏览器使用二进制上传。如果不设置,enctype属性默认为application/x-www-form-urlencoded,使用浏览器将使用ASCII向服务器发送数据,导致发送文件失败。上传文件要使用文件域(<input type='file'/>,并把FORM的Enctype设置为multipart/form-data.

⑺ springmvc文件上传路径设置

springmvc文件上传路径设置:1、导入文件上传的坐标。2、在spring-mvc.xml配置文件中配置文件解析器对象,property可以配置上传文件的大小等属性。注意:id一定要是multipartResolver。3、前端页面的form表单,method是post方法,加上enctype=”multipart/form-data”这个属性。4、后端方法的参数类型为MultipartFile,参数名要与前端文件域的name一样。5、最后用file参数的getOriginalFilename()方法获取上传的文件名,然后再用transferTo(参数1,参数2)方法将文件上传到指定路径。注:transferTo(参数1,参数2)的参数1为指定将文件上传的路径,参数2为文件名。

⑻ springmvc怎么实现多文件上传

多文件上传其实很简单,和上传其他相同的参数如checkbox一样,表单中使用相同的名称,然后action中将MultipartFile参数类定义为数组就可以。接下来实现:1、创建一个上传多文件的表单:在CODE上查看代码片派生到我的代码片<body><h2>上传多个文件 实例</h2><form action="filesUpload.html" method="post"enctype="multipart/form-data"><p>选择文件:<input type="file" name="files"><p>选择文件:<input type="file" name="files"><p>选择文件:<input type="file" name="files"><p><input type="submit" value="提交"></form></body> 2、编写处理表单的action,将原来保存文件的方法单独写一个方法出来方便共用:[java] view plain print?在CODE上查看代码片派生到我的代码片/**** 保存文件* @param file* @return*/private boolean saveFile(MultipartFile file) {// 判断文件是否为空if (!file.isEmpty()) {try {// 文件保存路径String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"+ file.getOriginalFilename();// 转存文件file.transferTo(new File(filePath));return true;} catch (Exception e) {e.printStackTrace();}}return false;}3、编写action:@RequestMapping("filesUpload")public String filesUpload(@RequestParam("files") MultipartFile[] files) {//判断file数组不能为空并且长度大于0if(files!=null&&files.length>0){//循环获取file数组中得文件for(int i = 0;i<files.length;i++){MultipartFile file = files[i];//保存文件saveFile(file);}}// 重定向return "redirect:/list.html";}

⑼ 求SpringMVC大文件上传详解及实例代码

SpringMVC的文件上传非常简便,首先导入文件上传依赖的jar:<!– 文件上传所依赖的jar包 –><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency> 在springMVC-servlet.xml配置文件中配置文件解析器:<!–1*1024*1024即1M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 –><!–文件上传解析器–><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="1048576"/><property name="defaultEncoding" value="UTF-8"/><property name="resolveLazily" value="true"/></bean>注意解析器的id必须等于multipartResolver,否则上传会出现异常import org.apache.commons.io.FileUtils;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;import org.springframework.web.multipart.commons.CommonsMultipartFile;import java.io.File;@Controllerpublic class FileController {/*** 上传单个文件操作* MultipartFile file就是上传的文件* @return*/@RequestMapping(value = "/upload1.html")public String fileUpload1(@RequestParam("file") MultipartFile file) {try {//将上传的文件存在E:/upload/下FileUtils.InputStreamToFile(file.getInputStream(), new File("E:/upload/",file.getOriginalFilename()));} catch (Exception e) {e.printStackTrace();}//上传成功返回原来页面return "/file.jsp";}}上传文件时,Controller的方法中参数类型是MultipartFile即可将文件映射到参数上。页面:file.jsp:<form method="post" action="/upload1.html" enctype="multipart/form-data"><input type="file" name="file"/><button type="submit" >提交</button></form>