在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ java后臺(tái),前端上傳的圖片,如何接受,并保存到服務(wù)器呀?

java后臺(tái),前端上傳的圖片,如何接受,并保存到服務(wù)器呀?

@RequestMapping(value = "/upload_img",method = {RequestMethod.GET, RequestMethod.POST},produces = "application/json; charset=utf-8")

@ResponseBody

public String upload_img(MultipartFile file,HttpServletRequest request) throws Exception{
    
    String path="/upload/news";
    
    //創(chuàng)建文件 
    File dir=new File(path);
    if(!dir.exists()){
        dir.mkdirs();
    }
    
    String id = SysUtil.getUUID();
    String fileName=file.getOriginalFilename();
  

    String img=id+fileName.substring(fileName.lastIndexOf("."));//zhao.jpg
    FileOutputStream imgOut=new FileOutputStream(new File(dir,img));//根據(jù) dir 抽象路徑名和 img 路徑名字符串創(chuàng)建一個(gè)新 File 實(shí)例。
   /* System.out.println(file.getBytes());*/
    imgOut.write(file.getBytes());//返回一個(gè)字節(jié)數(shù)組文件的內(nèi)容
    imgOut.close();
    Map<String, String> map=new HashMap<String, String>();
    map.put("path",img);
    return JSON.toJSONString(map);
}
回答
編輯回答
凝雅

在SpringMVC中文件上傳需要用到的jar包

  • commons-fileupload-1.2.2.jar
  • commons-io-2.4.jar

配置文件上傳解析器



    <!-- 文件上傳 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設(shè)置上傳文件的最大尺寸為5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

測(cè)試的JSP


<%--
  Created by IntelliJ IDEA.
  User: ozc
  Date: 2017/8/11
  Time: 9:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>測(cè)試文件上傳</title>
</head>
<body>


<form action="${pageContext.request.contextPath}/upload.action" method="post" enctype="multipart/form-data" >
    <input type="file" name="picture">
    <input type="submit" value="submit">
</form>

</body>
</html>

值得注意的是,在JSP的name屬性寫的是picture,那么在Controller方法參數(shù)的名稱也是要寫picture的,否則是獲取不到對(duì)應(yīng)的文件的..


@Controller
public class UploadController {
    @RequestMapping("/upload")
    //MultipartFile該對(duì)象就是封裝了圖片文件
    public void upload(MultipartFile picture) throws Exception {
        System.out.println(picture.getOriginalFilename());
    }
}
2017年8月29日 15:45