Não vou dizer muita bobagem, vou apenas postar o código para você. O código específico é o seguinte:
O código HTML é o seguinte:
<Body> <input id = "fileid" type = "file" aceit = "video/*; capture = camera" onchange = "onfile (this)"> <input id = "btn" type = "button" value = "submit"> <script type = "text/javascript"> var xhr; função onfile (arquivo) {var = " FormData (); fd.append ("fileTOUPLOAD", document.getElementById ('fileid'). Arquivos [0]); xhr = novo xmlhttprequest (); xhr.open ("post", "http: // localhost: 8889/testUp/upServlet"); // xhr.setRequestHeader ("content-type", "charset = utf-8"); xhr.send (fd); xhr.onStechange = ProcessResponsonsonsonsonse;} ProcessSonsonsone () {) (ifSToNeHaNead (IfSTonsonsensensensensend () (fd); End End Fream End "); if (xhr.status == 200) {var infer = xhr.PronseText; alert (" servidor lateral Response = "+Infor);}}} </Script> </body>O código Java se parece com o seguinte:
package com.yjm.up;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.httpServletReQuest; importar javax.servlet.http.httpServletResponse; importar org.apache.commons.fileupload.fileitem; import org.apache.commons.fileUpload.Disk.DiskEmilemory; org.apache.commons.fileupload.servlet.ServletFileUpload;public class UpServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Get the saved directory of the uploaded file, store the uploaded file in the WEB-INF A segurança do arquivo carregado String stringPath = this.getServletContext (). getRealPath ("/web-inf/upload"); arquivo file = new File (Salvarpath); System.out.out.println ("Test ..."); // Determine se o SAVED Directory do A UPROGELED FILHEUD FILHE FILE FILE ALMENTE ! file.isdirectory ()) {System.out.println (salvarpath + "O diretório não existe, precisa ser criado"); // Crie o diretório file.mkdir ();} // a mensagem solicita etapas de string = ""; try {// use o componente de upload do arquivo Apache para processar o arquivo de uplos: // 1. 1. DiskFileItemFactory (); // 2. Crie um abalador de upload de arquivo servletfileUpload upload = new ServletFileUpload (fábrica); // Resolva os chineses GLOBLED Upload.setheadeReCoding ("Utf-8"); // 3. {// Obtenha dados da maneira tradicional;} // 4. Use o analisador ServletFileUpload para analisar os dados enviados. O resultado da análise retorna uma lista <FileItem>. Cada FileItem corresponde ao item de entrada de uma lista de formulários <FileItem> list = upload.parserequest (request); para (item de fileItem: list) {// se os dados de um item de entrada normal estiverem encapsulados no arquivo if (item.isformfield ()) {string name = item.getfieldName (); // Resolva o problema chinês de dados de dados de entrada de entrada de entrada de string de string = item.getString ("utf-8") // // String (value.getBytes ("iso8859-1"), "utf-8"); system.out.println (name + "=" + value);} else {// se o item do arquivo encapsula o arquivo de nome (fIl); filename.trim (). Equals ("")) {continuação;} // Nota: Os nomes de arquivos enviados por diferentes navegadores são diferentes. Some browsers submit files with paths, such as: // c:/a/b/1.txt, and some are just simple file names, such as: 1.txt// Process the path part of the file name of the obtained uploaded file, only the file name part is retained filename = filename.substring(filename.lastIndexOf("//") + 1);// Get the input stream of the uploaded file in the item InputStream in = item.getInputStream (); // Crie um arquivo de saída de arquivo FileOutputStream Out = new FileOutputStream (Salvarpath + "//" + FileName); // Crie um buffer de buffer de buffer [] = novo byte [1024 * 1024]; // Crie um buffer buffer [] = novo [102424 * 1024]; FileOutputStream (SavePath + "//" + nome do arquivo); // Crie um buffer de buffer [] = novo byte [1024 * 1024]; // O identificador de determinar se os dados do fluxo de entrada foram lidos é int len = 0; // loop para ler o fluxo de entrada no buffer. (len = in.read (buffer))> 0 significa que ainda existem dados em whingo (len = in.read (buffer))> 0) {// use o fluxo de saída FileOutputStream para gravar os dados no buffer no diretório especificado (salvepath + "//" // + filename) out.write (buffer, 0, len); in.Close (); // Fechar o fluxo de saída fora.close (); // excluir o arquivo temporário gerado ao processar o arquivo de upload item.delete (); message = "Arquivo upload com sucesso!";}}} catch (Exceção e) {message = "upload de arquivo falhou!"; E.PrintStackTrace ();} request.setAttribute ("message", message); request.getRequestDispather ("/message.jsp").O pacote Java usado é carregado mais de 1g
Commons-FileUpload-1.2.1.jar
Commons-io-1.3.2.Jar
//xhr.SetRequestHeader("content-type","application/octet-stream ;charset=utf-8 "); Isso não pode ser adicionado