上传文件及参数

参考网址:http://www.tuicool.com/articles/2EnMBz



JAVA

package com.hmkcode.controllers;

import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.util.FileCopyUtils;

import com.hmkcode.vo.UploadedFile;

@Controller
@RequestMapping("/cont")
public class RestController {

  UploadedFile ufile;
  public RestController(){
  	System.out.println("init RestController");
  	ufile = new UploadedFile();
  }

  @RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
  public void get(HttpServletResponse response,@PathVariable String value){
 		try {

 		 	response.setContentType(ufile.type);
      response.setContentLength(ufile.length);
   		FileCopyUtils.copy(ufile.bytes, response.getOutputStream());

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

   @RequestMapping(value = "/upload", method = RequestMethod.POST)
   public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {                 

  	 //0. notice, we have used MultipartHttpServletRequest

  	 //1. get the file from the request object
   Iterator<String> itr =  request.getFileNames();

   MultipartFile mpf = request.getFile(itr.next());
  	 System.out.println(mpf.getOriginalFilename() +" uploaded!");

  	 try {
    ufile.length = mpf.getBytes().length;
    ufile.bytes= mpf.getBytes();
    	ufile.type = mpf.getContentType();
    	ufile.name = mpf.getOriginalFilename();

  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  	 //2. send it back to the client as <img> that calls get method
  	 //we are using getTimeInMillis to avoid server cached image 

  	 return "<img src='http://localhost:8080/spring-mvc-file-upload/rest/cont/get/"+Calendar.getInstance().getTimeInMillis()+"' />";

  }

}
配置文件

<beans .....>

  <context:component-scan base-package="com.hmkcode.controllers" />
  <mvc:annotation-driven />
  <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>

<script type="text/javascript" >

//using jquery.form.js
function uploadJqueryForm(){
    $('#result').html('');

   $("#form2").ajaxForm({
  success:function(data) { 
        //$('#result').text(data+" uploaded by Jquery Form plugin!");
        $('#result').html(data);

   },
   dataType:"text"
   }).submit();
}

HTML

 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://malsup.github.com/jquery.form.js"></script>
//using FormData() object
function uploadFormData(){
    $('#result').html('');

  var oMyForm = new FormData();
  oMyForm.append("file", file2.files[0]);

  $.ajax({
    url: '<strong>http://localhost:8080/spring-mvc-file-upload/rest/cont/upload</strong>',
    data: oMyForm,
    dataType: 'text',
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
    //  $('#result').html(data+ " uploaded by FormData!");
      $('#result').html(data);

    }
  });
}
&lt;/script&gt;
&lt;/head&gt;
<body>
<h1>SpringMVC - File Upload with/without Ajax</h1> 

<!--  Form 1 -->
<i>Uploading File Without Ajax</i><br/>
<form id="form1" method="post" action="/spring-mvc-file-upload/rest/cont/upload" enctype="multipart/form-data">

  <!-- File input -->     
  <input name="file" id="file" type="file" /><br/>

  <input type="submit" value="Upload" />
</form>
<hr/>
<i>Uploading File With Ajax</i><br/>

<!--  Form 2 -->
<form id="form2" method="post" action="/spring-mvc-file-upload/rest/cont/upload" enctype="multipart/form-data">
  <!-- File input -->     
  <input name="file2" id="file2" type="file" /><br/>
</form>

<button value="Submit" onclick="uploadJqueryForm()" >Upload</button><i>Using JQuery Form Plugin</i><br/>
<button value="Submit" onclick="uploadFormData()" >Upload</button><i>Using FormData Object</i>

<div id="result"></div>
</body>
</html>






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个非常流行的Java框架,提供了许多便捷的功能,包括文件上传和参数传递。 首先,我们需要使用Spring Boot的MultipartFile类来处理上传的文件。在Controller中使用@RequestBody注解,将MultipartHttpServletRequest对象作为参数传入方法中: @PostMapping("/upload") public String uploadFile(@RequestBody MultipartHttpServletRequest request) { MultipartFile file = request.getFile("file"); //处理上传的文件 return "success"; } 此外,我们还可以通过@RequestParam注解来传递其他参数,例如上传者的名称等: @PostMapping("/upload") public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { //处理上传的文件和参数 return "success"; } 在前端页面中,可以使用form表单来进行文件上传,也可以使用Ajax技术来实现异步上传。下面是一个使用jQuery的上传示例: $(document).on("change", "#file", function () { var formData = new FormData(); formData.append("name", $("#name").val()); formData.append("file", $("#file")[0].files[0]); $.ajax({ url: "/upload", type: "POST", processData: false, contentType: false, data: formData, success: function (result) { //上传成功后的操作 }, error: function (result) { //上传失败后的操作 } }); }); 在处理文件上传时,需要注意文件大小限制、文件格式限制等安全问题,以及文件上传进度的显示等用户体验问题。通过使用Spring Boot提供的便捷功能,可以大大简化文件上传和参数传递的过程,并提供更好的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值