js upload file back-end controller accepts

The upload file size is limited to servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">  
       <!-- 定义要扫描 controller的包 -->
       <context:component-scan base-package="control" />
       <!-- src下面的control   然后好找到controller -->

       <mvc:default-servlet-handler /> 
       <!-- 启动注解驱动 SpringMVC 功能 -->
       <mvc:annotation-driven />

       <!-- 配置视图解析器解析路径 -->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
              <!-- 定义视图存放路径 -->
              <property name="prefix" value="" />
             
       </bean>
       
       <!-- 
       <bean id="hql" class="control.hq" />
       <bean id="hqnr" class="control.hqnr" />
       <bean id="jiezhexie" class="control.dojiezhexie" />
       <bean id="panduan" class="control.dopanduan" />
       <bean id="hf6" class="control.dohf" />
       <bean id="jiemi6" class="control.dojiemi" />
       <bean id="map66" class="control.hqmap" />
       <bean id="tankuang" class="control.hqtankuang" />
       <bean id="upimg" class="control.doupimg" />
       <bean id="genggai" class="control.dohf" />
        -->
       <!-- xu yao zai zhe tian jia controller ,di yi ge shihan shu di er ge shi jie kou-->
       <!-- 上面的是原始的 下面的是现在用的  都在dohf中 -->
       
         
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- 默认最大不超过2M -->  
        <property name="maxUploadSize" value="10971520" />    
    </bean>  

</beans>

jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 <!DOCTYPE html><html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style type="text/css">
.c1{width:40px;height:60px;background-color:red;border: solid 1px green;float:left}
.c2{width:40px;height:60px;background-color:red;border: solid 1px green;float:left}
.c4{width:40px;height:60px;background-color:red;border: solid 1px green;float:left}
#main{border: solid 1px blue;border: solid 1px red;margin-top:60px;width:500px;height:450px;margin-left: auto;
    margin-right: auto;background-image:url(img/ff.png);
    background-size: 100% 100%;}
    .c{
    padding-top:130px;
    padding-left:90px;
    }
    .file{
    padding-left:90px;
    }
    .text{
    padding-left:90px;
    margin-left:90px;
    margin-top:40px;
    
    }
    .bt{
    background-color:green;
    margin-top:6px;
    margin-left:310px;
    height:42px;
    width:70px;
    }
    #img{
   
    margin-top:-260px;
    position:absolute;
    }
    .un{
    color:red;
    }
    
body {
	background-image: url(img/bg.jpg);background-attachment:fixed;left:0;background-size:100%;top:0;
background-repeat:no-repeat;background-size: cover;
}
</style>
</head>
<body>

<div id="main">
<% String un=(String)session.getAttribute("username");
int uid=0;
	if(un!=null){
	 uid=Integer.parseInt(session.getAttribute("userid").toString());//将session中的int类型转string后再转回int
//	int userid = Integer.parseInt(uid);
	out.print("<div class='c'><span class='un'>欢迎"+un+"</span></div>");
	} else{
	out.print("<div class='c'><a href='login.jsp'>想回复先登录login</a></div>");
	}
	

	%>	
<input type="file"  id="myFile1" class="file"/>
<br/>

<textarea id="text" placeholder="请填写内容" class="text" rows="10"></textarea>
<br/>
<button onclick="up()" class="bt">上传</button>
</div>
  <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=6DIkflz8yRoArw3e8VlsM786qiotww2o"></script>
<script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>  
<script src="http://api.map.baidu.com/api?v=2.0&ak=6DIkflz8yRoArw3e8VlsM786qiotww2o"></script>
<script type="text/javascript"></script>
<script type="text/javascript" src="jquery-1.7.1.js"></script>

<script> 

  
    function up(){
    
            var formData = new FormData(); 
formData.append('uploadfile_ant', $('#myFile1')[0].files[0]); 
if($('#myFile1')[0].files[0]==null){ //添加图片信息的参数
alert("没添加文件呢");
}
else{
var size=$('#myFile1')[0].files[0].size;
if(size>10000000){
alert($('#myFile1')[0].files[0].size);
}


else{
$.ajax({
    url: "film/uploadPic",
    //name: 'uploadfile_ant',
    type: 'POST',
    cache: false, //上传文件不需要缓存
    data: formData,
    processData: false, // 告诉jQuery不要去处理发送的数据
    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
    success: function (data) {
       // var c=eval("("+data+")");
       var nei="";
       for(var i=0;i<=data.length;i++){
       var dst=data[i].dst;
       nei=dst+nei;
       console.log(dst);
       }
       var ch=document.createTextNode(nei);
       var textarea=document.getElementById("text");
     textarea.appendChild(ch);
     setFocusLast(textarea);
    },
    error: function (data) {
        alert("上传失败");
    }
}); 
}
}
}
 
</script>

</body>
</html>

controller

package control;

//package uploadPicture;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import com.google.gson.Gson;

import bean.TransApi;
import bean.translate;
import bean.fanbean;
import bean.filedo;
/**
 * Created by Administrator on 2018/10/23.
 * @param <FileDomain>
 */

@Controller

public class cd {
    //文件类型
    public static String IMG_TYPE_PNG = "PNG";
    public static String IMG_TYPE_JPG = "JPG";
    public static String IMG_TYPE_JPEG = "JPEG";
   // public static String IMG_TYPE_DMG = "BMP";
    public static String IMG_TYPE_GIF = "GIF";
   // public static String IMG_TYPE_SVG = "SVG";
    private static final String APP_ID = "20200516000457621";
    private static final String SECURITY_KEY = "wZzFim__DILioHM5ahpp";
	  @RequestMapping("/film/uploadPic")
	    @ResponseBody
	    
	    public Object uploadPic(MultipartFile uploadfile_ant,HttpServletRequest request,HttpSession s6) throws Exception {
		  request.getSession().setAttribute("projectid","oo"); 
		  
		 // uploadfile_ant.
	        String oldName = uploadfile_ant.getOriginalFilename();
	        String newName = UUID.randomUUID().toString().replace("-", "").toUpperCase() 
	                + "_" + oldName;
	      String name=  uploadfile_ant.getOriginalFilename();
	      String filee=name.substring(name.lastIndexOf("."));//(name.lastIndexOf("."));//name.lastIndexOf(".");
	  
	      long size=uploadfile_ant.getSize();
	         System.out.print(size+"''''''''''''''''''''''''''''''''''''");
	      String temp_str="";
       	 Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
temp_str=sdf.format(dt);

String path=request.getServletContext().getRealPath("/upload/");
//System.out.println("上传的图片的newName: " + newName+",,,,,,"+temp_str+""+path);
	        File base = new File(path);
	        if (! base.exists()) {
	            base.mkdirs();
	        }
	        //if(!(filee.equals(IMG_TYPE_GIF)||filee.equals(IMG_TYPE_PNG)||filee.equals(IMG_TYPE_JPG)||filee.equals(IMG_TYPE_JPEG))){}
	        // 保存文件
	        
	        List<String> filelist=new ArrayList<String>();
	        //filelist.add(".png");
	        //filelist.add(".PNG");
	        //filelist.add(".JPG");
	        //filelist.add(".jpg");
	        //filelist.add(".JPEG");
	        filelist.add(".pdf");
	        HashMap s = new HashMap();
	        int i;
	        if(filelist.contains(filee)){
	        	String nr=null;
	        	ArrayList<translate> l=new ArrayList<translate>();
	        	uploadfile_ant.transferTo(new File(path + temp_str+filee));
	        	///
	        	File file = new File(path+temp_str+filee);//需要绝对路径
    	        FileInputStream in = null;
    	        try {
    	            in = new FileInputStream(path+temp_str+filee);//需要绝对路径
    	            // 新建一个PDF解析器对象
    	            PDFParser parser = new PDFParser(new RandomAccessFile(file,"rw"));
    	            // 对PDF文件进行解析
    	            parser.parse();
    	            // 获取解析后得到的PDF文档对象
    	            PDDocument pdfdocument = parser.getPDDocument();
    	            // 新建一个PDF文本剥离器
    	            PDFTextStripper stripper = new PDFTextStripper();
    	             
    	              int pagenumber=pdfdocument.getNumberOfPages();
    	              fanbean data=null;
    	              
    	              for(int ii=1;ii<=pagenumber;ii++){
    	            	  stripper.setSortByPosition(true);//WsetSortByPosition(sort); //sort设置为true 则按照行进行读取,默认是false
    	  	            // 从PDF文档对象中剥离文本
    	              stripper.setStartPage(ii);
    	              stripper.setEndPage(ii);
    	            String result = stripper.getText(pdfdocument);
    	            
    	            //FileWriter fileWriter = new FileWriter(new File("pdf.txt"));
    	            //fileWriter.write(result);
    	            //fileWriter.flush();
    	            //fileWriter.close();
    	            System.out.println("PDF文件的文本内容如下:"+result.length()+"页数"+pagenumber+"dangqian"+ii+"本页字数"+result.length()+"\r\n");
    	            String tishi="\r\n"+"PDF文件的文本内容如下:共"+result.length()+"字,有"+pagenumber+"页,当前是第"+ii+"页,本页有"+result.length()+"字"+"\r\n";
    	            System.out.println(result);
    	            
    	            try {
    	        		Thread.sleep(4000);
    	        	} catch (InterruptedException e) {
    	        		// TODO Auto-generated catch block
    	        		e.printStackTrace();
    	        	} //1000 毫秒权,也就是1秒.
    	        //    if(result.length()<6400){
    	            TransApi api = new TransApi(APP_ID, SECURITY_KEY);

    	            String query = "apple";
    	          //  System.out.println(api.getTransResult(query, "auto", "en"));
    	            String json = api.getTransResult(result, "auto", "zh");

    	            //通过gson解析
    	            Gson gson = new Gson();
    	             data = gson.fromJson(json,fanbean.class);
    	            String dst = data.getFrom();//getDst();
                    for(int ir=0;ir<data.getTrans_result().size();ir++){
                    	translate t=new translate();
                    	t.setDst(data.getTrans_result().get(ir).getDst());
                    	nr=data.getTrans_result().get(0).getDst();
    	            System.out.println(data.getTrans_result().get(ir).getDst());
    	            
    	            l.add(t);
                    System.out.println(l.get(0));
    	              }
    	              }}
    	              catch (Exception e) {
    	    	            System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败!" + e);
    	    	            e.printStackTrace();
    	    	        } finally {
    	    	            if (in != null) {
    	    	                try {
    	    	                    in.close();
    	    	                } catch (IOException e1) {
    	    	                }
    	    	            }
    	    	        }
	        	
	        	i=0;
	        	s.put("aaa", l);
	        	//s6.setAttribute("aaa", i);
	        
	        	s.put("src", temp_str+filee);
	        	//s.put("src","https://www.fuhufuhu.com/xcxmvc/upload/"+ temp_str+filee);
	        	//在服务器的配方
	        	
	        	
	        	//request.getSession().setAttribute("img",path+temp_str+filee); 
	        	//request.getSession().setAttribute("projectid","oo"); 
	        	return s;
	        }
	        
	        else{
	        	i=6;
	        s.put("aaa", i);
	        s6.setAttribute("aaa",i);
	    //    request.getSession().setAttribute("projectid","oo"); 
	        return s;
	        }
	       // }
			
	    }
	}


filedo

package beans;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class filedo {
	@Autowired
	private String description;
    private MultipartFile myfile;
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public MultipartFile getMyfile() {
        return myfile;
    }
    public void setMyfile(MultipartFile myfile) {
        this.myfile = myfile;
    }
	}

//————————————————
//版权声明:本文为CSDN博主「Asher1」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
//原文链接:https://blog.csdn.net/a447332241/article/details/75125305
//}

Guess you like

Origin blog.csdn.net/weixin_40938312/article/details/106193351