English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تنفيذ وظائف تحميل ومسح الملفات باستخدام Spring MVC

هذا المقال يشارككم الشيفرة المحددة لتحقيق ميزات تحميل و تنزيل الملفات باستخدام spring mvc، و يمكنكم الرجوع إليها، والتفاصيل كالتالي

تحميل الملفات

في pom.xml، قم بإدخال jar الخاص بـ spring mvc وcommons-fileupload

  <!-- spring mvc -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.3.13.RELEASE</version>
  </dependency>
  <!-- 文件上传与下载 -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
  </dependency>

在springmvc.xml中加入文件上传的相关配置

 <bean id="multipartResolver" 
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
  <!-- 上传文件大小上限,单位为字节(10MB) -->
  <property name="maxUploadSize"> 
   <value>10485760</value> 
  </property> 
  <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
  <property name="defaultEncoding">
   <value>UTF-8</value>
  </property>
 </bean>

在jsp文件中加入form表单

<form action="upload" enctype="multipart/form-data" method="post">
 <table>
  <tr>
   <td>文件描述:</td>
   <td><input type="text" name="description"></td>
  </tr>
  <tr>
   <td>请选择文件:</td>
   <td><input type="file" name="file"></td>
  </tr>
  <tr>
   <td><input type="submit" value="上传"></td>
  </tr>
 </table>
</form>

添加文件上传的方法

//上传文件会自动绑定到MultipartFile中
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest request,
  @RequestParam("description") String description,
  @RequestParam("file") MultipartFile file) throws Exception {
 //إذا كان الملف غير فارغ، يتم كتابة مسار التحميل
 if(!file.isEmpty()) {
  //مسار ملف التحميل
  String path = request.getServletContext().getRealPath("/file/");
  //اسم ملف التحميل
  String filename = file.getOriginalFilename();
  File filepath = new File(path,filename);
  //يتم التحقق من وجود المسار، إذا لم يكن موجودًا يتم إنشاؤه
  if (!filepath.getParentFile().exists()) {
   filepath.getParentFile().mkdirs();
  }
  //يتم حفظ ملف التحميل في ملف هدف
  file.transferTo(new File(path + File.separator + filename));
  return "success";
 } else {
  return "error";
 }
}

هذا هو نهاية محتوى هذا المقال، نأمل أن يكون قد ساعدكم في التعلم، ونأمل أن تشجعوا دروس النداء.

البيان: محتوى هذا المقال تم جمعه من الإنترنت، وملكه لصاحب الحقوق، تم جمعه من قبل المستخدمين على الإنترنت وتم تحميله بشكل تلقائي، لا يمتلك هذا الموقع حقوق الملكية، لم يتم تعديل المحتوى بشكل إنساني، ولا يتحمل هذا الموقع أي مسؤولية قانونية. إذا كنت قد وجدت محتوى يشتبه في انتهاك حقوق النسخ، فأنت مرحب بك في إرسال بريد إلكتروني إلى: notice#oldtoolbag.com (عند إرسال البريد الإلكتروني، يرجى استبدال '#' ب '@') للإبلاغ، وتقديم الأدلة ذات الصلة، وست�除 الموقع المتهمة من انتهاك حقوق النسخ في حال التحقق منها.

من المحتمل أن تفضل