上传文件及参数

参考网址: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>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值